Forecaster Module
Core forecasting classes and utilities.
spotforecast2_safe.forecaster
ForecasterBase
Bases: ABC
Base class for all forecasters in spotforecast2.
All forecasters should specify all the parameters that can be set at the class level in their init.
Attributes:
| Name | Type | Description |
|---|---|---|
__spotforecast_tags__ |
Dictionary with forecaster tags that characterize the behavior of the forecaster. |
Examples:
To see all abstract methods that need to be implemented:
>>> import inspect
>>> from spotforecast2_safe.forecaster.base import ForecasterBase
>>> [m[0] for m in inspect.getmembers(ForecasterBase, predicate=inspect.isabstract)]
['create_train_X_y', 'fit', 'predict', 'set_params']
Source code in src/spotforecast2_safe/forecaster/base.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | |
regressor
property
Deprecated property. Use estimator instead.
Returns:
| Type | Description |
|---|---|
Any
|
The estimator object. |
Examples:
__setstate__(state)
Custom setstate to ensure backward compatibility when unpickling.
This method is called when an object is unpickled (deserialized). It handles the migration of deprecated attributes to their new names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict
|
The state dictionary from the pickled object. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> import pickle
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> pickled_forecaster = pickle.dumps(forecaster)
>>> unpickled_forecaster = pickle.loads(pickled_forecaster)
Source code in src/spotforecast2_safe/forecaster/base.py
create_train_X_y(y, exog=None)
abstractmethod
Create training matrices from univariate time series and exogenous variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Series
|
Training time series. |
required |
exog
|
Series | DataFrame | None
|
Exogenous variable(s) included as predictor(s). Must have the same number of observations as y and their indexes must be aligned. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Tuple containing X_train (training values/predictors with shape |
Series
|
(len(y) - max_lag, len(lags))) and y_train (target values of the |
tuple[DataFrame, Series]
|
time series related to each row of X_train with shape (len(y) - max_lag,)). |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> import pandas as pd
>>> import numpy as np
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> y = pd.Series(np.arange(10), name='y')
>>> X_train, y_train = forecaster.create_train_X_y(y)
>>> X_train.head(2)
lag_1 lag_2 lag_3
3 2.0 1.0 0.0
4 3.0 2.0 1.0
>>> y_train.head(2)
3 3
4 4
Name: y, dtype: int64
Source code in src/spotforecast2_safe/forecaster/base.py
fit(y, exog=None)
abstractmethod
Training Forecaster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Series
|
Training time series. |
required |
exog
|
Series | DataFrame | None
|
Exogenous variable(s) included as predictor(s). Must have the same number of observations as y and their indexes must be aligned so that y[i] is regressed on exog[i]. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> import pandas as pd
>>> import numpy as np
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> y = pd.Series(np.arange(10), name='y')
>>> forecaster.fit(y)
>>> forecaster.is_fitted
True
Source code in src/spotforecast2_safe/forecaster/base.py
get_tags()
Return the tags that characterize the behavior of the forecaster.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with forecaster tags describing behavior and capabilities. |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> tags = forecaster.get_tags()
>>> tags['forecaster_task']
'regression'
Source code in src/spotforecast2_safe/forecaster/base.py
predict(steps, last_window=None, exog=None)
abstractmethod
Predict n steps ahead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int
|
Number of steps to predict. |
required |
last_window
|
Series | DataFrame | None
|
Series values used to create the predictors (lags) needed in the first iteration of the prediction (t + 1). If None, the values stored in last_window are used to calculate the initial predictors, and the predictions start right after training data. Default is None. |
None
|
exog
|
Series | DataFrame | None
|
Exogenous variable(s) included as predictor(s). Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
Series
|
Predicted values as a pandas Series. |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> import pandas as pd
>>> import numpy as np
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> y = pd.Series(np.arange(10), name='y')
>>> forecaster.fit(y)
>>> forecaster.predict(steps=3)
10 9.5
11 9.0
12 8.5
Name: pred, dtype: float64
Source code in src/spotforecast2_safe/forecaster/base.py
set_lags(lags=None)
Set new value to the attribute lags.
Attributes max_lag and window_size are also updated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lags
|
int | list[int] | ndarray[int] | range[int] | None
|
Lags used as predictors. Index starts at 1, so lag 1 is equal to t-1. If int: include lags from 1 to lags (included). If list, 1d numpy ndarray, or range: include only lags present in lags, all elements must be int. If None: no lags are included as predictors. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> forecaster.set_lags(lags=5)
>>> forecaster.lags
array([1, 2, 3, 4, 5])
Source code in src/spotforecast2_safe/forecaster/base.py
set_params(params)
abstractmethod
Set new values to the parameters of the scikit-learn model stored in the forecaster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict[str, object]
|
Parameters values dictionary. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> forecaster = ForecasterRecursive(estimator=Ridge(alpha=1.0), lags=3)
>>> forecaster.set_params({'estimator__alpha': 0.5})
>>> forecaster.estimator.alpha
0.5
Source code in src/spotforecast2_safe/forecaster/base.py
set_window_features(window_features=None)
Set new value to the attribute window_features.
Attributes max_size_window_features, window_features_names, window_features_class_names and window_size are also updated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_features
|
object | list[object] | None
|
Instance or list of instances used to create window features. Window features are created from the original time series and are included as predictors. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from spotforecast2_safe.forecaster.preprocessing import RollingFeatures
>>> from sklearn.linear_model import Ridge
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> window_feat = RollingFeatures(stats='mean', window_sizes=3)
>>> forecaster.set_window_features(window_features=window_feat)
>>> forecaster.window_features
[RollingFeatures(stats=['mean'], window_sizes=[3])]
Source code in src/spotforecast2_safe/forecaster/base.py
summary()
Show forecaster information.
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> forecaster.summary()
ForecasterRecursive
===================
Estimator: Ridge()
Lags: [1 2 3]
...
Source code in src/spotforecast2_safe/forecaster/base.py
ForecasterRecursive
Bases: ForecasterBase
Recursive autoregressive forecaster for scikit-learn compatible estimators.
This class turns any estimator compatible with the scikit-learn API into a recursive autoregressive (multi-step) forecaster. The forecaster learns to predict future values by using lagged values of the target variable and optional exogenous features. Predictions are made iteratively, where each step uses previous predictions as input for the next step (recursive strategy).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
object
|
Scikit-learn compatible estimator for regression. If None, a default estimator will be initialized. Can also be passed via regressor parameter. |
None
|
lags
|
Union[int, List[int], ndarray, range, None]
|
Lagged values of the target variable to use as predictors. Can be an integer (uses lags from 1 to lags), list of integers, numpy array, or range. At least one of lags or window_features must be provided. Defaults to None. |
None
|
window_features
|
Union[object, List[object], None]
|
List of window feature objects to compute features from the target variable. Each object must implement transform_batch() method. At least one of lags or window_features must be provided. Defaults to None. |
None
|
transformer_y
|
Optional[object]
|
Transformer object for the target variable. Must implement fit() and transform() methods. Applied before training and predictions. Defaults to None. |
None
|
transformer_exog
|
Optional[object]
|
Transformer object for exogenous variables. Must implement fit() and transform() methods. Applied before training and predictions. Defaults to None. |
None
|
weight_func
|
Optional[Callable]
|
Function to compute sample weights for training. Must accept an index and return an array of weights. Defaults to None. |
None
|
differentiation
|
Optional[int]
|
Order of differencing to apply to the target variable. Must be a positive integer. Differencing is applied before creating lags. Defaults to None. |
None
|
fit_kwargs
|
Optional[Dict[str, object]]
|
Dictionary of additional keyword arguments to pass to the estimator's fit() method. Defaults to None. |
None
|
binner_kwargs
|
Optional[Dict[str, object]]
|
Dictionary of keyword arguments for QuantileBinner used in probabilistic predictions. Defaults to {'n_bins': 10, 'method': 'linear'}. |
None
|
forecaster_id
|
Union[str, int, None]
|
Identifier for the forecaster instance. Can be a string or integer. Used for tracking and logging purposes. Defaults to None. |
None
|
regressor
|
object
|
Alternative parameter name for estimator. If provided, used instead of estimator. Defaults to None. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
estimator |
Fitted scikit-learn estimator. |
|
lags |
Lag indices used in the model. |
|
lags_names |
Names of lag features (e.g., ['lag_1', 'lag_2']). |
|
window_features |
List of window feature transformers. |
|
window_features_names |
Names of window features. |
|
window_size |
Maximum window size needed (max of lags and window features). |
|
transformer_y |
Transformer for target variable. |
|
transformer_exog |
Transformer for exogenous variables. |
|
weight_func |
Function for sample weighting. |
|
differentiation |
Order of differencing applied. |
|
differentiator |
TimeSeriesDifferentiator instance if differencing is used. |
|
is_fitted |
Boolean indicating if forecaster has been fitted. |
|
fit_date |
Timestamp of the last fit operation. |
|
last_window_ |
Last window_size observations from training data. |
|
index_type_ |
Type of index in training data (RangeIndex or DatetimeIndex). |
|
index_freq_ |
Frequency of DatetimeIndex if applicable. |
|
training_range_ |
First and last index values of training data. |
|
series_name_in_ |
Name of the target series. |
|
exog_in_ |
Boolean indicating if exogenous variables were used in training. |
|
exog_names_in_ |
Names of exogenous variables. |
|
exog_type_in_ |
Type of exogenous input (Series or DataFrame). |
|
X_train_features_names_out_ |
Names of all training features. |
|
in_sample_residuals_ |
Residuals from training set. |
|
in_sample_residuals_by_bin_ |
Residuals grouped by bins for probabilistic pred. |
|
forecaster_id |
Identifier for the forecaster instance. |
Note
- Either lags or window_features (or both) must be provided during initialization.
- The forecaster uses a recursive strategy where each multi-step prediction depends on previous predictions within the same forecast horizon.
- Exogenous variables must have the same index as the target variable and must be available for the entire prediction horizon.
- The forecaster supports point predictions, prediction intervals, bootstrapping, quantile predictions, and probabilistic forecasts via conformal methods.
Examples:
Create a basic forecaster with lags:
>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> y = pd.Series(np.random.randn(100), name='y')
>>> forecaster = ForecasterRecursive(
... estimator=LinearRegression(),
... lags=10
... )
>>> forecaster.fit(y)
>>> predictions = forecaster.predict(steps=5)
Create a forecaster with window features and transformations:
>>> from sklearn.ensemble import RandomForestRegressor
>>> from sklearn.preprocessing import StandardScaler
>>> from spotforecast2_safe.preprocessing import RollingFeatures
>>> import pandas as pd
>>> y = pd.Series(np.random.randn(100), name='y')
>>> forecaster = ForecasterRecursive(
... estimator=RandomForestRegressor(n_estimators=100),
... lags=[1, 7, 30],
... window_features=[RollingFeatures(stats='mean', window_sizes=7)],
... transformer_y=StandardScaler(),
... differentiation=1
... )
>>> forecaster.fit(y)
>>> predictions = forecaster.predict(steps=10)
Create a forecaster with exogenous variables:
>>> import pandas as pd
>>> from sklearn.linear_model import Ridge
>>> y = pd.Series(np.random.randn(100), name='target')
>>> exog = pd.DataFrame({'temp': np.random.randn(100)}, index=y.index)
>>> forecaster = ForecasterRecursive(
... estimator=Ridge(),
... lags=7,
... forecaster_id='my_forecaster'
... )
>>> forecaster.fit(y, exog)
>>> exog_future = pd.DataFrame(
... {'temp': np.random.randn(5)},
... index=pd.RangeIndex(start=100, stop=105)
... )
>>> predictions = forecaster.predict(steps=5, exog=exog_future)
Create a forecaster with probabilistic prediction configuration:
>>> from sklearn.ensemble import GradientBoostingRegressor
>>> import pandas as pd
>>> y = pd.Series(np.random.randn(100), name='y')
>>> forecaster = ForecasterRecursive(
... estimator=GradientBoostingRegressor(),
... lags=14,
... binner_kwargs={'n_bins': 15, 'method': 'linear'}
... )
>>> forecaster.fit(y, store_in_sample_residuals=True)
>>> predictions = forecaster.predict(steps=5)
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 | |
__repr__()
Information displayed when a ForecasterRecursive object is printed.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
String representation of the forecaster with key information about its configuration and state. |
Examples:
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> print(forecaster)
=========================
ForecasterRecursive
=========================
Estimator: LinearRegression
Lags: [1, 2, 3]
Window features: []
Window size: 3
Series name: None
Exogenous included: False
Exogenous names: None
Transformer for y: None
Transformer for exog: None
Weight function included: False
Differentiation order: None
Training range: None
Training index type: None
Training index frequency: None
Estimator parameters: {...}
fit_kwargs: {...}
Creation date: ...
Last fit date: None
spotforecast version: ...
Python version: ...
Forecaster id: None
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
__setstate__(state)
Custom setstate to ensure backward compatibility when unpickling. Only sets spotforecast_tags if not present, preserving custom tags.
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
create_predict_X(steps, last_window=None, exog=None, check_inputs=True)
Create the predictors needed to predict steps ahead. As it is a recursive
process, the predictors are created at each iteration of the prediction
process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int
|
Number of steps to predict. - If steps is int, number of steps to predict. - If str or pandas Datetime, the prediction will be up to that date. |
required |
last_window
|
Series | DataFrame | None
|
Series values used to create the predictors (lags) needed in the
first iteration of the prediction (t + 1).
If |
None
|
exog
|
Series | DataFrame | None
|
Exogenous variable/s included as predictor/s. Defaults to None. |
None
|
check_inputs
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Pandas DataFrame with the predictors for each step. The index |
DataFrame
|
is the same as the prediction index. |
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 | |
create_sample_weights(X_train)
Create weights for each observation according to the forecaster's attribute
weight_func.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_train
|
DataFrame
|
Dataframe created with the |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Weights to use in |
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
create_train_X_y(y, exog=None)
Public method to create training predictors and target values.
This method is a public wrapper around the internal method _create_train_X_y,
which generates the training predictors and target values based on the provided time series and exogenous variables.
It ensures that the necessary transformations and feature engineering steps are applied to prepare the data for training the forecaster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Series
|
Target series for training. Must be a pandas Series. |
required |
exog
|
Union[Series, DataFrame, None]
|
Optional exogenous variables for training. Can be a pandas Series or DataFrame. Must have the same index as |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[DataFrame, Series]
|
Tuple containing: - X_train: DataFrame of training predictors including lags, window features, and exogenous variables (if provided). - y_train: Series of target values aligned with the predictors. |
Examples:
>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from spotforecast2_safe.preprocessing import RollingFeatures
>>> y = pd.Series(np.arange(30), name='y')
>>> exog = pd.DataFrame({'temp': np.random.randn(30)}, index=y.index)
>>> forecaster = ForecasterRecursive(
... estimator=LinearRegression(),
... lags=3,
... window_features=[RollingFeatures(stats='mean', window_sizes=3)]
... )
>>> X_train, y_train = forecaster.create_train_X_y(y=y, exog=exog)
>>> isinstance(X_train, pd.DataFrame)
True
>>> isinstance(y_train, pd.Series)
True
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
fit(y, exog=None, store_last_window=True, store_in_sample_residuals=False, random_state=123, suppress_warnings=False)
Fit the forecaster to the training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Series
|
Target series for training. Must be a pandas Series. |
required |
exog
|
Union[Series, DataFrame, None]
|
Optional exogenous variables for training. Can be a pandas Series or DataFrame.Must have the same index as |
None
|
store_last_window
|
bool
|
Whether to store the last window of the training series for use in prediction. Defaults to True. |
True
|
store_in_sample_residuals
|
bool
|
Whether to store in-sample residuals after fitting, which can be used for certain probabilistic prediction methods. Defaults to False. |
False
|
random_state
|
int
|
Random seed for reproducibility when sampling residuals if |
123
|
suppress_warnings
|
bool
|
Whether to suppress warnings during fitting, such as those related to insufficient data length for lags or window features. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from spotforecast2_safe.preprocessing import RollingFeatures
>>> y = pd.Series(np.arange(30), name='y')
>>> exog = pd.DataFrame({'temp': np.random.randn(30)}, index=y.index)
>>> forecaster = ForecasterRecursive(
... estimator=LinearRegression(),
... lags=3,
... window_features=[RollingFeatures(stats='mean', window_sizes=3)]
... )
>>> forecaster.fit(y=y, exog=exog, store_in_sample_residuals=True)
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 | |
get_feature_importances(sort_importance=True)
Return feature importances of the estimator stored in the forecaster.
Only valid when estimator stores internally the feature importances in the
attribute feature_importances_ or coef_. Otherwise, returns None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sort_importance
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Feature importances associated with each predictor. |
Raises:
| Type | Description |
|---|---|
NotFittedError
|
If the forecaster is not fitted. |
Examples:
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> import pandas as pd
>>> import numpy as np
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> forecaster.fit(y=pd.Series(np.arange(20)))
>>> forecaster.get_feature_importances()
feature importance
0 lag_1 1.0
1 lag_2 0.0
2 lag_3 0.0
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 | |
get_params(deep=True)
Get parameters for this forecaster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
deep
|
bool
|
If True, will return the parameters for this forecaster and contained sub-objects that are estimators. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
params |
Dict[str, object]
|
Dictionary of parameter names mapped to their values. |
Examples:
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> forecaster.get_params()
{
'estimator': LinearRegression(), 'lags': 3, 'window_features': None,
'transformer_y': None, 'transformer_exog': None, 'weight_func': None,
'differentiation': None, 'fit_kwargs': {}, 'binner_kwargs': None, 'forecaster_id': '...'}
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
predict(steps, last_window=None, exog=None, check_inputs=True)
Predict future values recursively for the specified number of steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int | str | Timestamp
|
Number of future steps to predict. |
required |
last_window
|
Union[Series, DataFrame, None]
|
Optional last window of observed values to use for prediction. If None, uses the last window from training. Must be a pandas Series or DataFrame with the same structure as the training target series. Defaults to None. |
None
|
exog
|
Union[Series, DataFrame, None]
|
Optional exogenous variables for prediction. Can be a pandas Series or DataFrame. Must have the same structure as the exogenous variables used in training. Defaults to None. |
None
|
check_inputs
|
bool
|
Whether to perform input validation checks. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
Series
|
Pandas Series of predicted values for the specified number of steps, |
Series
|
indexed according to the prediction index constructed from the last window and the number of steps. |
Examples:
>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from spotforecast2_safe.preprocessing import RollingFeatures
>>> y = pd.Series(np.arange(30), name='y')
>>> exog = pd.DataFrame({'temp': np.random.randn(30)}, index=y.index)
>>> forecaster = ForecasterRecursive(
... estimator=LinearRegression(),
... lags=3,
... window_features=[RollingFeatures(stats='mean', window_sizes=3)]
... )
>>> forecaster.fit(y=y, exog=exog)
>>> last_window = y.iloc[-3:]
>>> exog_future = pd.DataFrame({'temp': np.random.randn(5)}, index=pd.RangeIndex(start=30, stop=35))
>>> predictions = forecaster.predict(
... steps=5, last_window=last_window, exog=exog_future, check_inputs=True
... )
>>> isinstance(predictions, pd.Series)
True
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 | |
predict_bootstrapping(steps, last_window=None, exog=None, n_boot=250, use_in_sample_residuals=True, use_binned_residuals=True, random_state=123)
Generate multiple forecasting predictions using a bootstrapping process. By sampling from a collection of past observed errors (the residuals), each iteration of bootstrapping generates a different set of predictions. See the References section for more information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int | str | Timestamp
|
Number of steps to predict. - If steps is int, number of steps to predict. - If str or pandas Datetime, the prediction will be up to that date. |
required |
last_window
|
Series | DataFrame | None
|
Series values used to create the predictors (lags) needed in the
first iteration of the prediction (t + 1).
If |
None
|
exog
|
Series | DataFrame | None
|
Exogenous variable/s included as predictor/s. Defaults to None. |
None
|
n_boot
|
int
|
Number of bootstrapping iterations to perform when estimating prediction intervals. Defaults to 250. |
250
|
use_in_sample_residuals
|
bool
|
If |
True
|
use_binned_residuals
|
bool
|
If |
True
|
random_state
|
int
|
Seed for the random number generator to ensure reproducibility. Defaults to 123. |
123
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Pandas DataFrame with predictions generated by bootstrapping. Shape: (steps, n_boot). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ValueError
|
If |
ValueError
|
If |
ValueError
|
If |
ValueError
|
If |
Examples:
>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> rng = np.random.default_rng(123)
>>> y = pd.Series(rng.normal(size=100), name='y')
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> _ = forecaster.fit(y=y)
>>> boot_preds = forecaster.predict_bootstrapping(steps=3, n_boot=5)
>>> boot_preds.shape
(3, 5)
References
.. [1] Forecasting: Principles and Practice (3rd ed) Rob J Hyndman and George Athanasopoulos. https://otexts.com/fpp3/prediction-intervals.html
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 | |
predict_dist(steps, distribution, last_window=None, exog=None, n_boot=250, use_in_sample_residuals=True, use_binned_residuals=True, random_state=123)
Fit a given probability distribution for each step. After generating multiple forecasting predictions through a bootstrapping process, each step is fitted to the given distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int | str | Timestamp
|
Number of steps to predict. - If steps is int, number of steps to predict. - If str or pandas Datetime, the prediction will be up to that date. |
required |
distribution
|
object
|
A distribution object from scipy.stats with methods |
required |
last_window
|
Series | DataFrame | None
|
Series values used to create the predictors (lags) needed in the
first iteration of the prediction (t + 1).
If |
None
|
exog
|
Series | DataFrame | None
|
Exogenous variable/s included as predictor/s. |
None
|
n_boot
|
int
|
Number of bootstrapping iterations to perform when estimating prediction intervals. |
250
|
use_in_sample_residuals
|
bool
|
If |
True
|
use_binned_residuals
|
bool
|
If |
True
|
random_state
|
int
|
Seed for the random number generator to ensure reproducibility. |
123
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Distribution parameters estimated for each step. |
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 | |
predict_interval(steps, last_window=None, exog=None, method='bootstrapping', interval=[5, 95], n_boot=250, use_in_sample_residuals=True, use_binned_residuals=True, random_state=123)
Predict n steps ahead and estimate prediction intervals using either bootstrapping or conformal prediction methods. Refer to the References section for additional details on these methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int | str | Timestamp
|
Number of steps to predict. - If steps is int, number of steps to predict. - If str or pandas Datetime, the prediction will be up to that date. |
required |
last_window
|
Series | DataFrame | None
|
Series values used to create the predictors (lags) needed in the
first iteration of the prediction (t + 1).
If |
None
|
exog
|
Series | DataFrame | None
|
Exogenous variable/s included as predictor/s. Defaults to None. |
None
|
method
|
str
|
Technique used to estimate prediction intervals. Available options: - 'bootstrapping': Bootstrapping is used to generate prediction intervals [1]. - 'conformal': Employs the conformal prediction split method for interval estimation [2]. Defaults to 'bootstrapping'. |
'bootstrapping'
|
interval
|
float | list[float] | tuple[float]
|
Confidence level of the prediction interval. Interpretation depends
on the method used:
- If |
[5, 95]
|
n_boot
|
int
|
Number of bootstrapping iterations to perform when estimating prediction intervals. Defaults to 250. |
250
|
use_in_sample_residuals
|
bool
|
If |
True
|
use_binned_residuals
|
bool
|
If |
True
|
random_state
|
int
|
Seed for the random number generator to ensure reproducibility. Defaults to 123. |
123
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Pandas DataFrame with values predicted by the forecaster and their estimated interval. |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ValueError
|
If |
ValueError
|
If inputs ( |
Examples:
>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> rng = np.random.default_rng(123)
>>> y = pd.Series(rng.normal(size=100), name='y')
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> _ = forecaster.fit(y=y)
>>> # Bootstrapping method
>>> intervals_boot = forecaster.predict_interval(
... steps=3, method='bootstrapping', interval=[5, 95]
... )
>>> intervals_boot.columns.tolist()
['pred', 'lower_bound', 'upper_bound']
>>> # Conformal method
>>> intervals_conf = forecaster.predict_interval(
... steps=3, method='conformal', interval=0.95
... )
>>> intervals_conf.columns.tolist()
['pred', 'lower_bound', 'upper_bound']
References
.. [1] Forecasting: Principles and Practice (3rd ed) Rob J Hyndman and George Athanasopoulos. https://otexts.com/fpp3/prediction-intervals.html .. [2] MAPIE - Model Agnostic Prediction Interval Estimator. https://mapie.readthedocs.io/en/stable/theoretical_description_regression.html#the-split-method
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 | |
predict_quantiles(steps, last_window=None, exog=None, quantiles=[0.05, 0.5, 0.95], n_boot=250, use_in_sample_residuals=True, use_binned_residuals=True, random_state=123)
Calculate the specified quantiles for each step. After generating multiple forecasting predictions through a bootstrapping process, each quantile is calculated for each step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int | str | Timestamp
|
Number of steps to predict. - If steps is int, number of steps to predict. - If str or pandas Datetime, the prediction will be up to that date. |
required |
last_window
|
Series | DataFrame | None
|
Series values used to create the predictors (lags) needed in the
first iteration of the prediction (t + 1).
If |
None
|
exog
|
Series | DataFrame | None
|
Exogenous variable/s included as predictor/s. |
None
|
quantiles
|
list[float] | tuple[float]
|
Sequence of quantiles to compute, which must be between 0 and 1
inclusive. For example, quantiles of 0.05, 0.5 and 0.95 should be as
|
[0.05, 0.5, 0.95]
|
n_boot
|
int
|
Number of bootstrapping iterations to perform when estimating quantiles. |
250
|
use_in_sample_residuals
|
bool
|
If |
True
|
use_binned_residuals
|
bool
|
If |
True
|
random_state
|
int
|
Seed for the random number generator to ensure reproducibility. |
123
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Quantiles predicted by the forecaster. |
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
set_fit_kwargs(fit_kwargs)
Set new values for the additional keyword arguments passed to the fit
method of the estimator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fit_kwargs
|
dict[str, object]
|
Dict of the form {"argument": new_value}. |
required |
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
set_in_sample_residuals(y, exog=None, random_state=123)
Set in-sample residuals in case they were not calculated during the training process.
In-sample residuals are calculated as the difference between the true values and the predictions made by the forecaster using the training data. The following internal attributes are updated:
in_sample_residuals_: residuals stored in a numpy ndarray.binner_intervals_: intervals used to bin the residuals are calculated using the quantiles of the predicted values.in_sample_residuals_by_bin_: residuals are binned according to the predicted value they are associated with and stored in a dictionary, where the keys are the intervals of the predicted values and the values are the residuals associated with that range.
A total of 10_000 residuals are stored in the attribute in_sample_residuals_.
If the number of residuals is greater than 10_000, a random sample of
10_000 residuals is stored. The number of residuals stored per bin is
limited to 10_000 // self.binner.n_bins_.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Series
|
Target time series. |
required |
exog: Exogenous variables.
random_state: Random state for reproducibility.
Returns:
| Type | Description |
|---|---|
None
|
None |
Raises:
| Type | Description |
|---|---|
NotFittedError
|
If the forecaster is not fitted. |
IndexError
|
If the index range of |
ValueError
|
If the features generated from the provided data do not match those used during the training process. |
Examples:
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> forecaster.fit(y=pd.Series(np.arange(20)), store_in_sample_residuals=False)
>>> forecaster.set_in_sample_residuals(y=pd.Series(np.arange(20)))
>>> forecaster.in_sample_residuals_
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 | |
set_lags(lags=None)
Set new value to the attribute lags. Attributes lags_names,
max_lag and window_size are also updated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lags
|
Union[int, List[int], ndarray, range, None]
|
Lags used as predictors. Index starts at 1, so lag 1 is equal to t-1.
- |
None
|
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
set_out_sample_residuals(y_true, y_pred, append=False, random_state=123)
Set new values to the attribute out_sample_residuals_.
Out of sample residuals are meant to be calculated using observations that
did not participate in the training process. y_true and y_pred are
expected to be in the original scale of the time series. Residuals are
calculated as y_true - y_pred, after applying the necessary
transformations and differentiations if the forecaster includes them
(self.transformer_y and self.differentiation). Two internal attributes
are updated:
out_sample_residuals_: residuals stored in a numpy ndarray.out_sample_residuals_by_bin_: residuals are binned according to the predicted value they are associated with and stored in a dictionary, where the keys are the intervals of the predicted values and the values are the residuals associated with that range. If a bin is empty, it is filled with a random sample of residuals from other bins. This is done to ensure that all bins have at least one residual and can be used in the prediction process.
A total of 10_000 residuals are stored in the attribute out_sample_residuals_.
If the number of residuals is greater than 10_000, a random sample of
10_000 residuals is stored. The number of residuals stored per bin is
limited to 10_000 // self.binner.n_bins_.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
ndarray | Series
|
True values of the time series in the original scale. |
required |
y_pred
|
ndarray | Series
|
Predicted values of the time series in the original scale. |
required |
append
|
bool
|
If |
False
|
random_state
|
int
|
Random state for reproducibility. |
123
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Raises:
| Type | Description |
|---|---|
NotFittedError
|
If the forecaster is not fitted. |
TypeError
|
If |
ValueError
|
If |
Examples:
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> import pandas as pd
>>> import numpy as np
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> forecaster.fit(y=pd.Series(np.arange(20)), store_in_sample_residuals=False)
>>> y_true = np.array([20, 21, 22, 23, 24])
>>> y_pred = np.array([20.1, 20.9, 22.2, 22.8, 24.0])
>>> forecaster.set_out_sample_residuals(y_true=y_true, y_pred=y_pred)
>>> forecaster.out_sample_residuals_
array([-0.1, 0.1, -0.2, 0.2, 0. ])
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 | |
set_params(params=None, **kwargs)
Set the parameters of this forecaster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
Dict[str, object]
|
Optional dictionary of parameter names mapped to their new values. If provided, these parameters are set first. |
None
|
**kwargs
|
object
|
Dictionary of parameter names mapped to their new values.
Parameters can be for the forecaster itself or for the contained estimator (using the |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
'ForecasterRecursive'
|
The forecaster instance with updated parameters. |
Examples:
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> forecaster.set_params(estimator__fit_intercept=False)
>>> forecaster.estimator.get_params()["fit_intercept"]
False
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
set_window_features(window_features=None)
Set new value to the attribute window_features. Attributes
max_size_window_features, window_features_names,
window_features_class_names and window_size are also updated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_features
|
object | list[object] | None
|
Instance or list of instances used to create window features. Window features are created from the original time series and are included as predictors. |
None
|
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
Base Forecaster
base
spotforecast2_safe.forecaster.base
ForecasterBase class.
This module contains the base class for all forecasters in spotforecast2_safe and spotforecast. All forecasters should specify all the parameters that can be set at the class level in their init.
Examples:
Create a custom forecaster inheriting from ForecasterBase:
>>> from spotforecast2_safe.forecaster.base import ForecasterBase
>>> import pandas as pd
>>> import numpy as np
>>> class MyForecaster(ForecasterBase):
... def __init__(self, estimator):
... self.estimator = estimator
... self.__spotforecast_tags__ = {'hide_lags': True}
... def create_train_X_y(self, y, exog=None):
... return pd.DataFrame(), pd.Series(dtype=float)
... def fit(self, y, exog=None):
... pass
... def predict(self, steps, last_window=None, exog=None):
... return pd.Series(np.zeros(steps))
... def set_params(self, params):
... pass
>>> from sklearn.linear_model import Ridge
>>> forecaster = MyForecaster(estimator=Ridge())
>>> forecaster
MyForecaster(estimator=Ridge())
ForecasterBase
Bases: ABC
Base class for all forecasters in spotforecast2.
All forecasters should specify all the parameters that can be set at the class level in their init.
Attributes:
| Name | Type | Description |
|---|---|---|
__spotforecast_tags__ |
Dictionary with forecaster tags that characterize the behavior of the forecaster. |
Examples:
To see all abstract methods that need to be implemented:
>>> import inspect
>>> from spotforecast2_safe.forecaster.base import ForecasterBase
>>> [m[0] for m in inspect.getmembers(ForecasterBase, predicate=inspect.isabstract)]
['create_train_X_y', 'fit', 'predict', 'set_params']
Source code in src/spotforecast2_safe/forecaster/base.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | |
regressor
property
Deprecated property. Use estimator instead.
Returns:
| Type | Description |
|---|---|
Any
|
The estimator object. |
Examples:
__setstate__(state)
Custom setstate to ensure backward compatibility when unpickling.
This method is called when an object is unpickled (deserialized). It handles the migration of deprecated attributes to their new names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict
|
The state dictionary from the pickled object. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> import pickle
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> pickled_forecaster = pickle.dumps(forecaster)
>>> unpickled_forecaster = pickle.loads(pickled_forecaster)
Source code in src/spotforecast2_safe/forecaster/base.py
create_train_X_y(y, exog=None)
abstractmethod
Create training matrices from univariate time series and exogenous variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Series
|
Training time series. |
required |
exog
|
Series | DataFrame | None
|
Exogenous variable(s) included as predictor(s). Must have the same number of observations as y and their indexes must be aligned. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Tuple containing X_train (training values/predictors with shape |
Series
|
(len(y) - max_lag, len(lags))) and y_train (target values of the |
tuple[DataFrame, Series]
|
time series related to each row of X_train with shape (len(y) - max_lag,)). |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> import pandas as pd
>>> import numpy as np
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> y = pd.Series(np.arange(10), name='y')
>>> X_train, y_train = forecaster.create_train_X_y(y)
>>> X_train.head(2)
lag_1 lag_2 lag_3
3 2.0 1.0 0.0
4 3.0 2.0 1.0
>>> y_train.head(2)
3 3
4 4
Name: y, dtype: int64
Source code in src/spotforecast2_safe/forecaster/base.py
fit(y, exog=None)
abstractmethod
Training Forecaster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Series
|
Training time series. |
required |
exog
|
Series | DataFrame | None
|
Exogenous variable(s) included as predictor(s). Must have the same number of observations as y and their indexes must be aligned so that y[i] is regressed on exog[i]. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> import pandas as pd
>>> import numpy as np
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> y = pd.Series(np.arange(10), name='y')
>>> forecaster.fit(y)
>>> forecaster.is_fitted
True
Source code in src/spotforecast2_safe/forecaster/base.py
get_tags()
Return the tags that characterize the behavior of the forecaster.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with forecaster tags describing behavior and capabilities. |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> tags = forecaster.get_tags()
>>> tags['forecaster_task']
'regression'
Source code in src/spotforecast2_safe/forecaster/base.py
predict(steps, last_window=None, exog=None)
abstractmethod
Predict n steps ahead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int
|
Number of steps to predict. |
required |
last_window
|
Series | DataFrame | None
|
Series values used to create the predictors (lags) needed in the first iteration of the prediction (t + 1). If None, the values stored in last_window are used to calculate the initial predictors, and the predictions start right after training data. Default is None. |
None
|
exog
|
Series | DataFrame | None
|
Exogenous variable(s) included as predictor(s). Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
Series
|
Predicted values as a pandas Series. |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> import pandas as pd
>>> import numpy as np
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> y = pd.Series(np.arange(10), name='y')
>>> forecaster.fit(y)
>>> forecaster.predict(steps=3)
10 9.5
11 9.0
12 8.5
Name: pred, dtype: float64
Source code in src/spotforecast2_safe/forecaster/base.py
set_lags(lags=None)
Set new value to the attribute lags.
Attributes max_lag and window_size are also updated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lags
|
int | list[int] | ndarray[int] | range[int] | None
|
Lags used as predictors. Index starts at 1, so lag 1 is equal to t-1. If int: include lags from 1 to lags (included). If list, 1d numpy ndarray, or range: include only lags present in lags, all elements must be int. If None: no lags are included as predictors. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> forecaster.set_lags(lags=5)
>>> forecaster.lags
array([1, 2, 3, 4, 5])
Source code in src/spotforecast2_safe/forecaster/base.py
set_params(params)
abstractmethod
Set new values to the parameters of the scikit-learn model stored in the forecaster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict[str, object]
|
Parameters values dictionary. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> forecaster = ForecasterRecursive(estimator=Ridge(alpha=1.0), lags=3)
>>> forecaster.set_params({'estimator__alpha': 0.5})
>>> forecaster.estimator.alpha
0.5
Source code in src/spotforecast2_safe/forecaster/base.py
set_window_features(window_features=None)
Set new value to the attribute window_features.
Attributes max_size_window_features, window_features_names, window_features_class_names and window_size are also updated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_features
|
object | list[object] | None
|
Instance or list of instances used to create window features. Window features are created from the original time series and are included as predictors. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from spotforecast2_safe.forecaster.preprocessing import RollingFeatures
>>> from sklearn.linear_model import Ridge
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> window_feat = RollingFeatures(stats='mean', window_sizes=3)
>>> forecaster.set_window_features(window_features=window_feat)
>>> forecaster.window_features
[RollingFeatures(stats=['mean'], window_sizes=[3])]
Source code in src/spotforecast2_safe/forecaster/base.py
summary()
Show forecaster information.
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from sklearn.linear_model import Ridge
>>> forecaster = ForecasterRecursive(estimator=Ridge(), lags=3)
>>> forecaster.summary()
ForecasterRecursive
===================
Estimator: Ridge()
Lags: [1 2 3]
...
Source code in src/spotforecast2_safe/forecaster/base.py
Recursive Forecasting
recursive
spotforecast2_safe.forecaster.recursive
ForecasterEquivalentDate
This forecaster predicts future values based on the most recent equivalent date. It also allows to aggregate multiple past values of the equivalent date using a function (e.g. mean, median, max, min, etc.). The equivalent date is calculated by moving back in time a specified number of steps (offset). The offset can be defined as an integer or as a pandas DateOffset. This approach is useful as a baseline, but it is a simplistic method and may not capture complex underlying patterns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
offset
|
(int, DateOffset)
|
Number of steps to go back
in time to find the most recent equivalent date to the target period.
If |
required |
n_offsets
|
int
|
Number of equivalent dates (multiple of offset)
used in the prediction. Defaults to 1.
If |
1
|
agg_func
|
Callable
|
Function used to aggregate the values of the
equivalent dates when the number of equivalent dates ( |
mean
|
binner_kwargs
|
dict
|
Additional arguments to pass to the
|
None
|
forecaster_id
|
(str, int)
|
Name used as an identifier of the forecaster. Defaults to None. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
offset |
(int, DateOffset)
|
Number of steps to go back in time to find the most recent equivalent date to the target period. |
n_offsets |
int
|
Number of equivalent dates (multiple of offset) used in the prediction. |
agg_func |
Callable
|
Function used to aggregate the values of the equivalent
dates when the number of equivalent dates ( |
window_size |
int
|
Number of past values needed to include the last
equivalent dates according to the |
last_window_ |
pandas Series
|
This window represents the most recent data
observed by the predictor during its training phase. It contains the
past values needed to include the last equivalent date according the
|
index_type_ |
type
|
Type of index of the input used in training. |
index_freq_ |
str
|
Frequency of Index of the input used in training. |
training_range_ |
pandas Index
|
First and last values of index of the data used during training. |
series_name_in_ |
str
|
Names of the series provided by the user during training. |
in_sample_residuals_ |
numpy ndarray
|
Residuals of the model when predicting training data. Only stored up to 10_000 values. |
in_sample_residuals_by_bin_ |
dict
|
In sample residuals binned according to
the predicted value each residual is associated with. The number of
residuals stored per bin is limited to |
out_sample_residuals_ |
numpy ndarray
|
Residuals of the model when predicting
non-training data. Only stored up to 10_000 values. Use
|
out_sample_residuals_by_bin_ |
dict
|
Out of sample residuals binned
according to the predicted value each residual is associated with.
The number of residuals stored per bin is limited to
|
binner |
QuantileBinner
|
|
binner_intervals_ |
dict
|
Intervals used to discretize residuals into k bins according to the predicted values associated with each residual. |
binner_kwargs |
dict
|
Additional arguments to pass to the |
creation_date |
str
|
Date of creation. |
is_fitted |
bool
|
Tag to identify if the estimator has been fitted (trained). |
fit_date |
str
|
Date of last fit. |
spotforecast_version |
str
|
Version of spotforecast library used to create the forecaster. |
python_version |
str
|
Version of python used to create the forecaster. |
forecaster_id |
(str, int)
|
Name used as an identifier of the forecaster. |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from spotforecast2_safe.forecaster.recursive import ForecasterEquivalentDate
>>> # Series with daily frequency
>>> data = pd.Series(
... data = np.arange(14),
... index = pd.date_range(start='2022-01-01', periods=14, freq='D')
... )
>>> # Forecast based on the value 7 days ago
>>> forecaster = ForecasterEquivalentDate(offset=7)
>>> forecaster.fit(y=data)
>>> forecaster.predict(steps=3)
2022-01-15 7
2022-01-16 8
2022-01-17 9
Freq: D, Name: pred, dtype: int64
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_equivalent_date.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 | |
__repr__()
Information displayed when a Forecaster object is printed.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Information about the forecaster. It contains the following information: |
str
|
|
|
str
|
|
|
str
|
|
|
str
|
|
|
str
|
|
|
str
|
|
|
str
|
|
|
str
|
|
|
str
|
|
|
str
|
|
|
str
|
|
|
str
|
|
|
str
|
|
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from spotforecast2_safe.forecaster.recursive import ForecasterEquivalentDate
>>> data = pd.Series(
... data = np.arange(14),
... index = pd.date_range(start='2022-01-01', periods=14, freq='D')
... )
>>> forecaster = ForecasterEquivalentDate(offset=7)
>>> forecaster.fit(y=data)
>>> print(forecaster)
============================
ForecasterEquivalentDate
============================
Offset: 7
Number of offsets: 1
Aggregation function: mean
Window size: 7
Series name: y
Training range: [Timestamp('2022-01-01 00:00:00'), Timestamp('2022-01-14 00:00:00')]
Training index type: DatetimeIndex
Training index frequency: D
Creation date: 2023-11-19 12:00:00
Last fit date: 2023-11-19 12:00:00
spotforecast version: 1.0.0
Python version: 3.8.10
Forecaster id: None
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_equivalent_date.py
fit(y, store_in_sample_residuals=False, random_state=123, exog=None)
Training Forecaster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
pandas Series
|
Training time series. |
required |
store_in_sample_residuals
|
bool
|
If |
False
|
random_state
|
int
|
Set a seed for the random generator so that the stored sample residuals are always deterministic. Defaults to 123. |
123
|
exog
|
Ignored
|
Not used, present here for API consistency by convention. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from spotforecast2_safe.forecaster.recursive import ForecasterEquivalentDate
>>> data = pd.Series(
... data = np.arange(14),
... index = pd.date_range(start='2022-01-01', periods=14, freq='D')
... )
>>> forecaster = ForecasterEquivalentDate(offset=7)
>>> forecaster.fit(y=data)
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_equivalent_date.py
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 | |
get_tags()
Return the tags that characterize the behavior of the forecaster.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, Any]
|
Dictionary with forecaster tags. |
Examples:
>>> from spotforecast2_safe.forecaster.recursive import ForecasterEquivalentDate
>>> forecaster = ForecasterEquivalentDate(offset=7)
>>> tags = forecaster.get_tags()
>>> sorted(tags.keys())[:3]
['allowed_input_types_exog', 'allowed_input_types_series', 'forecaster_name']
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_equivalent_date.py
predict(steps, last_window=None, check_inputs=True, exog=None)
Predict n steps ahead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int
|
Number of steps to predict. |
required |
last_window
|
pandas Series
|
Past values needed to select the
last equivalent dates according to the offset. If |
None
|
check_inputs
|
bool
|
If |
True
|
exog
|
Ignored
|
Not used, present here for API consistency by convention. |
None
|
Returns:
| Type | Description |
|---|---|
Series
|
pd.Series: Predicted values. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If all equivalent values are missing when using a pandas DateOffset as offset.
This can be caused by using an offset larger than the available data.
To avoid this, try to decrease the size of the offset, the number of |
Warning
|
If some equivalent values are missing when using a pandas DateOffset as offset.
This can be caused by using an offset larger than the available data or by using an |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from spotforecast2_safe.forecaster.recursive import ForecasterEquivalentDate
>>> data = pd.Series(
... data = np.arange(14),
... index = pd.date_range(start='2022-01-01', periods=14, freq='D')
... )
>>> forecaster = ForecasterEquivalentDate(offset=7)
>>> forecaster.fit(y=data)
>>> forecaster.predict(steps=3)
2022-01-15 7
2022-01-16 8
2022-01-17 9
Freq: D, Name: pred, dtype: int64
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_equivalent_date.py
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 | |
predict_interval(steps, last_window=None, method='conformal', interval=[5, 95], use_in_sample_residuals=True, use_binned_residuals=True, random_state=None, exog=None, n_boot=None)
Predict n steps ahead and estimate prediction intervals using conformal prediction method. Refer to the References section for additional details on this method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int
|
Number of steps to predict. |
required |
last_window
|
pandas Series
|
Past values needed to select the
last equivalent dates according to the offset. If |
None
|
method
|
str
|
Technique used to estimate prediction intervals. Available options: - 'conformal': Employs the conformal prediction split method for interval estimation [1]_. Defaults to 'conformal'. |
'conformal'
|
interval
|
(float, list, tuple)
|
Confidence level of the
prediction interval. Interpretation depends on the method used:
- If |
[5, 95]
|
use_in_sample_residuals
|
bool
|
If |
True
|
use_binned_residuals
|
bool
|
If |
True
|
random_state
|
Ignored
|
Not used, present here for API consistency by convention. |
None
|
exog
|
Ignored
|
Not used, present here for API consistency by convention. |
None
|
n_boot
|
Ignored
|
Not used, present here for API consistency by convention. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Values predicted by the forecaster and their estimated interval. - pred: predictions. - lower_bound: lower bound of the interval. - upper_bound: upper bound of the interval. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ValueError
|
If |
References
.. [1] MAPIE - Model Agnostic Prediction Interval Estimator. https://mapie.readthedocs.io/en/stable/theoretical_description_regression.html#the-split-method
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from spotforecast2_safe.forecaster.recursive import ForecasterEquivalentDate
>>> data = pd.Series(
... data = np.arange(14, dtype=float),
... index = pd.date_range(start='2022-01-01', periods=14, freq='D')
... )
>>> forecaster = ForecasterEquivalentDate(offset=7)
>>> forecaster.fit(y=data, store_in_sample_residuals=True)
>>> forecaster.predict_interval(steps=3, interval=0.8)
pred lower_bound upper_bound
2022-01-15 7.0 6.0 8.0
2022-01-16 8.0 7.0 9.0
2022-01-17 9.0 8.0 10.0
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_equivalent_date.py
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 | |
set_in_sample_residuals(y, random_state=123, exog=None)
Set in-sample residuals in case they were not calculated during the training process.
In-sample residuals are calculated as the difference between the true values and the predictions made by the forecaster using the training data. The following internal attributes are updated:
in_sample_residuals_: residuals stored in a numpy ndarray.binner_intervals_: intervals used to bin the residuals are calculated using the quantiles of the predicted values.in_sample_residuals_by_bin_: residuals are binned according to the predicted value they are associated with and stored in a dictionary, where the keys are the intervals of the predicted values and the values are the residuals associated with that range.
A total of 10_000 residuals are stored in the attribute in_sample_residuals_.
If the number of residuals is greater than 10_000, a random sample of
10_000 residuals is stored. The number of residuals stored per bin is
limited to 10_000 // self.binner.n_bins_.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
pandas Series
|
Training time series. |
required |
random_state
|
int
|
Sets a seed to the random sampling for reproducible output. Defaults to 123. |
123
|
exog
|
Ignored
|
Not used, present here for API consistency by convention. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Raises:
| Type | Description |
|---|---|
NotFittedError
|
If the forecaster has not been fitted. |
IndexError
|
If the index range of |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from spotforecast2_safe.forecaster.recursive import ForecasterEquivalentDate
>>> data = pd.Series(
... data=np.arange(14, dtype=float),
... index=pd.date_range(start="2022-01-01", periods=14, freq="D"),
... )
>>> forecaster = ForecasterEquivalentDate(offset=7)
>>> forecaster.fit(y=data)
>>> # Recompute and store residuals if needed
>>> forecaster.set_in_sample_residuals(y=data, random_state=123)
>>> forecaster.in_sample_residuals_.shape
(7,)
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_equivalent_date.py
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 | |
set_out_sample_residuals(y_true, y_pred, append=False, random_state=123)
Set new values to the attribute out_sample_residuals_. Out of sample
residuals are meant to be calculated using observations that did not
participate in the training process. Two internal attributes are updated:
out_sample_residuals_: residuals stored in a numpy ndarray.out_sample_residuals_by_bin_: residuals are binned according to the predicted value they are associated with and stored in a dictionary, where the keys are the intervals of the predicted values and the values are the residuals associated with that range. If a bin binning is empty, it is filled with a random sample of residuals from other bins. This is done to ensure that all bins have at least one residual and can be used in the prediction process.
A total of 10_000 residuals are stored in the attribute out_sample_residuals_.
If the number of residuals is greater than 10_000, a random sample of
10_000 residuals is stored. The number of residuals stored per bin is
limited to 10_000 // self.binner.n_bins_.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
numpy ndarray, pandas Series
|
True values of the time series from which the residuals have been calculated. |
required |
y_pred
|
numpy ndarray, pandas Series
|
Predicted values of the time series. |
required |
append
|
bool
|
If |
False
|
random_state
|
int
|
Sets a seed to the random sampling for reproducible output. Defaults to 123. |
123
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Raises:
| Type | Description |
|---|---|
NotFittedError
|
If the forecaster has not been fitted. |
TypeError
|
If |
ValueError
|
If |
ValueError
|
If |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from spotforecast2_safe.forecaster.recursive import ForecasterEquivalentDate
>>> data = pd.Series(
... data=np.arange(21, dtype=float),
... index=pd.date_range(start="2022-01-01", periods=21, freq="D"),
... )
>>> forecaster = ForecasterEquivalentDate(offset=7)
>>> forecaster.fit(y=data)
>>> preds = forecaster.predict(steps=7)
>>> y_true = pd.Series(data[-7:].to_numpy(), index=preds.index)
>>> forecaster.set_out_sample_residuals(y_true=y_true, y_pred=preds)
>>> forecaster.out_sample_residuals_.shape
(7,)
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_equivalent_date.py
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 | |
summary()
Show forecaster information.
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from spotforecast2_safe.forecaster.recursive import ForecasterEquivalentDate
>>> data = pd.Series(
... data=np.arange(14, dtype=float),
... index=pd.date_range(start="2022-01-01", periods=14, freq="D"),
... )
>>> forecaster = ForecasterEquivalentDate(offset=7)
>>> forecaster.fit(y=data)
>>> forecaster.summary()
============================
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_equivalent_date.py
ForecasterRecursive
Bases: ForecasterBase
Recursive autoregressive forecaster for scikit-learn compatible estimators.
This class turns any estimator compatible with the scikit-learn API into a recursive autoregressive (multi-step) forecaster. The forecaster learns to predict future values by using lagged values of the target variable and optional exogenous features. Predictions are made iteratively, where each step uses previous predictions as input for the next step (recursive strategy).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
object
|
Scikit-learn compatible estimator for regression. If None, a default estimator will be initialized. Can also be passed via regressor parameter. |
None
|
lags
|
Union[int, List[int], ndarray, range, None]
|
Lagged values of the target variable to use as predictors. Can be an integer (uses lags from 1 to lags), list of integers, numpy array, or range. At least one of lags or window_features must be provided. Defaults to None. |
None
|
window_features
|
Union[object, List[object], None]
|
List of window feature objects to compute features from the target variable. Each object must implement transform_batch() method. At least one of lags or window_features must be provided. Defaults to None. |
None
|
transformer_y
|
Optional[object]
|
Transformer object for the target variable. Must implement fit() and transform() methods. Applied before training and predictions. Defaults to None. |
None
|
transformer_exog
|
Optional[object]
|
Transformer object for exogenous variables. Must implement fit() and transform() methods. Applied before training and predictions. Defaults to None. |
None
|
weight_func
|
Optional[Callable]
|
Function to compute sample weights for training. Must accept an index and return an array of weights. Defaults to None. |
None
|
differentiation
|
Optional[int]
|
Order of differencing to apply to the target variable. Must be a positive integer. Differencing is applied before creating lags. Defaults to None. |
None
|
fit_kwargs
|
Optional[Dict[str, object]]
|
Dictionary of additional keyword arguments to pass to the estimator's fit() method. Defaults to None. |
None
|
binner_kwargs
|
Optional[Dict[str, object]]
|
Dictionary of keyword arguments for QuantileBinner used in probabilistic predictions. Defaults to {'n_bins': 10, 'method': 'linear'}. |
None
|
forecaster_id
|
Union[str, int, None]
|
Identifier for the forecaster instance. Can be a string or integer. Used for tracking and logging purposes. Defaults to None. |
None
|
regressor
|
object
|
Alternative parameter name for estimator. If provided, used instead of estimator. Defaults to None. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
estimator |
Fitted scikit-learn estimator. |
|
lags |
Lag indices used in the model. |
|
lags_names |
Names of lag features (e.g., ['lag_1', 'lag_2']). |
|
window_features |
List of window feature transformers. |
|
window_features_names |
Names of window features. |
|
window_size |
Maximum window size needed (max of lags and window features). |
|
transformer_y |
Transformer for target variable. |
|
transformer_exog |
Transformer for exogenous variables. |
|
weight_func |
Function for sample weighting. |
|
differentiation |
Order of differencing applied. |
|
differentiator |
TimeSeriesDifferentiator instance if differencing is used. |
|
is_fitted |
Boolean indicating if forecaster has been fitted. |
|
fit_date |
Timestamp of the last fit operation. |
|
last_window_ |
Last window_size observations from training data. |
|
index_type_ |
Type of index in training data (RangeIndex or DatetimeIndex). |
|
index_freq_ |
Frequency of DatetimeIndex if applicable. |
|
training_range_ |
First and last index values of training data. |
|
series_name_in_ |
Name of the target series. |
|
exog_in_ |
Boolean indicating if exogenous variables were used in training. |
|
exog_names_in_ |
Names of exogenous variables. |
|
exog_type_in_ |
Type of exogenous input (Series or DataFrame). |
|
X_train_features_names_out_ |
Names of all training features. |
|
in_sample_residuals_ |
Residuals from training set. |
|
in_sample_residuals_by_bin_ |
Residuals grouped by bins for probabilistic pred. |
|
forecaster_id |
Identifier for the forecaster instance. |
Note
- Either lags or window_features (or both) must be provided during initialization.
- The forecaster uses a recursive strategy where each multi-step prediction depends on previous predictions within the same forecast horizon.
- Exogenous variables must have the same index as the target variable and must be available for the entire prediction horizon.
- The forecaster supports point predictions, prediction intervals, bootstrapping, quantile predictions, and probabilistic forecasts via conformal methods.
Examples:
Create a basic forecaster with lags:
>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> y = pd.Series(np.random.randn(100), name='y')
>>> forecaster = ForecasterRecursive(
... estimator=LinearRegression(),
... lags=10
... )
>>> forecaster.fit(y)
>>> predictions = forecaster.predict(steps=5)
Create a forecaster with window features and transformations:
>>> from sklearn.ensemble import RandomForestRegressor
>>> from sklearn.preprocessing import StandardScaler
>>> from spotforecast2_safe.preprocessing import RollingFeatures
>>> import pandas as pd
>>> y = pd.Series(np.random.randn(100), name='y')
>>> forecaster = ForecasterRecursive(
... estimator=RandomForestRegressor(n_estimators=100),
... lags=[1, 7, 30],
... window_features=[RollingFeatures(stats='mean', window_sizes=7)],
... transformer_y=StandardScaler(),
... differentiation=1
... )
>>> forecaster.fit(y)
>>> predictions = forecaster.predict(steps=10)
Create a forecaster with exogenous variables:
>>> import pandas as pd
>>> from sklearn.linear_model import Ridge
>>> y = pd.Series(np.random.randn(100), name='target')
>>> exog = pd.DataFrame({'temp': np.random.randn(100)}, index=y.index)
>>> forecaster = ForecasterRecursive(
... estimator=Ridge(),
... lags=7,
... forecaster_id='my_forecaster'
... )
>>> forecaster.fit(y, exog)
>>> exog_future = pd.DataFrame(
... {'temp': np.random.randn(5)},
... index=pd.RangeIndex(start=100, stop=105)
... )
>>> predictions = forecaster.predict(steps=5, exog=exog_future)
Create a forecaster with probabilistic prediction configuration:
>>> from sklearn.ensemble import GradientBoostingRegressor
>>> import pandas as pd
>>> y = pd.Series(np.random.randn(100), name='y')
>>> forecaster = ForecasterRecursive(
... estimator=GradientBoostingRegressor(),
... lags=14,
... binner_kwargs={'n_bins': 15, 'method': 'linear'}
... )
>>> forecaster.fit(y, store_in_sample_residuals=True)
>>> predictions = forecaster.predict(steps=5)
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 | |
__repr__()
Information displayed when a ForecasterRecursive object is printed.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
String representation of the forecaster with key information about its configuration and state. |
Examples:
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> print(forecaster)
=========================
ForecasterRecursive
=========================
Estimator: LinearRegression
Lags: [1, 2, 3]
Window features: []
Window size: 3
Series name: None
Exogenous included: False
Exogenous names: None
Transformer for y: None
Transformer for exog: None
Weight function included: False
Differentiation order: None
Training range: None
Training index type: None
Training index frequency: None
Estimator parameters: {...}
fit_kwargs: {...}
Creation date: ...
Last fit date: None
spotforecast version: ...
Python version: ...
Forecaster id: None
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
__setstate__(state)
Custom setstate to ensure backward compatibility when unpickling. Only sets spotforecast_tags if not present, preserving custom tags.
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
create_predict_X(steps, last_window=None, exog=None, check_inputs=True)
Create the predictors needed to predict steps ahead. As it is a recursive
process, the predictors are created at each iteration of the prediction
process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int
|
Number of steps to predict. - If steps is int, number of steps to predict. - If str or pandas Datetime, the prediction will be up to that date. |
required |
last_window
|
Series | DataFrame | None
|
Series values used to create the predictors (lags) needed in the
first iteration of the prediction (t + 1).
If |
None
|
exog
|
Series | DataFrame | None
|
Exogenous variable/s included as predictor/s. Defaults to None. |
None
|
check_inputs
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Pandas DataFrame with the predictors for each step. The index |
DataFrame
|
is the same as the prediction index. |
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 | |
create_sample_weights(X_train)
Create weights for each observation according to the forecaster's attribute
weight_func.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_train
|
DataFrame
|
Dataframe created with the |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Weights to use in |
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
create_train_X_y(y, exog=None)
Public method to create training predictors and target values.
This method is a public wrapper around the internal method _create_train_X_y,
which generates the training predictors and target values based on the provided time series and exogenous variables.
It ensures that the necessary transformations and feature engineering steps are applied to prepare the data for training the forecaster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Series
|
Target series for training. Must be a pandas Series. |
required |
exog
|
Union[Series, DataFrame, None]
|
Optional exogenous variables for training. Can be a pandas Series or DataFrame. Must have the same index as |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[DataFrame, Series]
|
Tuple containing: - X_train: DataFrame of training predictors including lags, window features, and exogenous variables (if provided). - y_train: Series of target values aligned with the predictors. |
Examples:
>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from spotforecast2_safe.preprocessing import RollingFeatures
>>> y = pd.Series(np.arange(30), name='y')
>>> exog = pd.DataFrame({'temp': np.random.randn(30)}, index=y.index)
>>> forecaster = ForecasterRecursive(
... estimator=LinearRegression(),
... lags=3,
... window_features=[RollingFeatures(stats='mean', window_sizes=3)]
... )
>>> X_train, y_train = forecaster.create_train_X_y(y=y, exog=exog)
>>> isinstance(X_train, pd.DataFrame)
True
>>> isinstance(y_train, pd.Series)
True
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
fit(y, exog=None, store_last_window=True, store_in_sample_residuals=False, random_state=123, suppress_warnings=False)
Fit the forecaster to the training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Series
|
Target series for training. Must be a pandas Series. |
required |
exog
|
Union[Series, DataFrame, None]
|
Optional exogenous variables for training. Can be a pandas Series or DataFrame.Must have the same index as |
None
|
store_last_window
|
bool
|
Whether to store the last window of the training series for use in prediction. Defaults to True. |
True
|
store_in_sample_residuals
|
bool
|
Whether to store in-sample residuals after fitting, which can be used for certain probabilistic prediction methods. Defaults to False. |
False
|
random_state
|
int
|
Random seed for reproducibility when sampling residuals if |
123
|
suppress_warnings
|
bool
|
Whether to suppress warnings during fitting, such as those related to insufficient data length for lags or window features. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from spotforecast2_safe.preprocessing import RollingFeatures
>>> y = pd.Series(np.arange(30), name='y')
>>> exog = pd.DataFrame({'temp': np.random.randn(30)}, index=y.index)
>>> forecaster = ForecasterRecursive(
... estimator=LinearRegression(),
... lags=3,
... window_features=[RollingFeatures(stats='mean', window_sizes=3)]
... )
>>> forecaster.fit(y=y, exog=exog, store_in_sample_residuals=True)
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 | |
get_feature_importances(sort_importance=True)
Return feature importances of the estimator stored in the forecaster.
Only valid when estimator stores internally the feature importances in the
attribute feature_importances_ or coef_. Otherwise, returns None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sort_importance
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Feature importances associated with each predictor. |
Raises:
| Type | Description |
|---|---|
NotFittedError
|
If the forecaster is not fitted. |
Examples:
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> import pandas as pd
>>> import numpy as np
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> forecaster.fit(y=pd.Series(np.arange(20)))
>>> forecaster.get_feature_importances()
feature importance
0 lag_1 1.0
1 lag_2 0.0
2 lag_3 0.0
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 | |
get_params(deep=True)
Get parameters for this forecaster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
deep
|
bool
|
If True, will return the parameters for this forecaster and contained sub-objects that are estimators. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
params |
Dict[str, object]
|
Dictionary of parameter names mapped to their values. |
Examples:
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> forecaster.get_params()
{
'estimator': LinearRegression(), 'lags': 3, 'window_features': None,
'transformer_y': None, 'transformer_exog': None, 'weight_func': None,
'differentiation': None, 'fit_kwargs': {}, 'binner_kwargs': None, 'forecaster_id': '...'}
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
predict(steps, last_window=None, exog=None, check_inputs=True)
Predict future values recursively for the specified number of steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int | str | Timestamp
|
Number of future steps to predict. |
required |
last_window
|
Union[Series, DataFrame, None]
|
Optional last window of observed values to use for prediction. If None, uses the last window from training. Must be a pandas Series or DataFrame with the same structure as the training target series. Defaults to None. |
None
|
exog
|
Union[Series, DataFrame, None]
|
Optional exogenous variables for prediction. Can be a pandas Series or DataFrame. Must have the same structure as the exogenous variables used in training. Defaults to None. |
None
|
check_inputs
|
bool
|
Whether to perform input validation checks. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
Series
|
Pandas Series of predicted values for the specified number of steps, |
Series
|
indexed according to the prediction index constructed from the last window and the number of steps. |
Examples:
>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from spotforecast2_safe.preprocessing import RollingFeatures
>>> y = pd.Series(np.arange(30), name='y')
>>> exog = pd.DataFrame({'temp': np.random.randn(30)}, index=y.index)
>>> forecaster = ForecasterRecursive(
... estimator=LinearRegression(),
... lags=3,
... window_features=[RollingFeatures(stats='mean', window_sizes=3)]
... )
>>> forecaster.fit(y=y, exog=exog)
>>> last_window = y.iloc[-3:]
>>> exog_future = pd.DataFrame({'temp': np.random.randn(5)}, index=pd.RangeIndex(start=30, stop=35))
>>> predictions = forecaster.predict(
... steps=5, last_window=last_window, exog=exog_future, check_inputs=True
... )
>>> isinstance(predictions, pd.Series)
True
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 | |
predict_bootstrapping(steps, last_window=None, exog=None, n_boot=250, use_in_sample_residuals=True, use_binned_residuals=True, random_state=123)
Generate multiple forecasting predictions using a bootstrapping process. By sampling from a collection of past observed errors (the residuals), each iteration of bootstrapping generates a different set of predictions. See the References section for more information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int | str | Timestamp
|
Number of steps to predict. - If steps is int, number of steps to predict. - If str or pandas Datetime, the prediction will be up to that date. |
required |
last_window
|
Series | DataFrame | None
|
Series values used to create the predictors (lags) needed in the
first iteration of the prediction (t + 1).
If |
None
|
exog
|
Series | DataFrame | None
|
Exogenous variable/s included as predictor/s. Defaults to None. |
None
|
n_boot
|
int
|
Number of bootstrapping iterations to perform when estimating prediction intervals. Defaults to 250. |
250
|
use_in_sample_residuals
|
bool
|
If |
True
|
use_binned_residuals
|
bool
|
If |
True
|
random_state
|
int
|
Seed for the random number generator to ensure reproducibility. Defaults to 123. |
123
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Pandas DataFrame with predictions generated by bootstrapping. Shape: (steps, n_boot). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ValueError
|
If |
ValueError
|
If |
ValueError
|
If |
ValueError
|
If |
Examples:
>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> rng = np.random.default_rng(123)
>>> y = pd.Series(rng.normal(size=100), name='y')
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> _ = forecaster.fit(y=y)
>>> boot_preds = forecaster.predict_bootstrapping(steps=3, n_boot=5)
>>> boot_preds.shape
(3, 5)
References
.. [1] Forecasting: Principles and Practice (3rd ed) Rob J Hyndman and George Athanasopoulos. https://otexts.com/fpp3/prediction-intervals.html
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 | |
predict_dist(steps, distribution, last_window=None, exog=None, n_boot=250, use_in_sample_residuals=True, use_binned_residuals=True, random_state=123)
Fit a given probability distribution for each step. After generating multiple forecasting predictions through a bootstrapping process, each step is fitted to the given distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int | str | Timestamp
|
Number of steps to predict. - If steps is int, number of steps to predict. - If str or pandas Datetime, the prediction will be up to that date. |
required |
distribution
|
object
|
A distribution object from scipy.stats with methods |
required |
last_window
|
Series | DataFrame | None
|
Series values used to create the predictors (lags) needed in the
first iteration of the prediction (t + 1).
If |
None
|
exog
|
Series | DataFrame | None
|
Exogenous variable/s included as predictor/s. |
None
|
n_boot
|
int
|
Number of bootstrapping iterations to perform when estimating prediction intervals. |
250
|
use_in_sample_residuals
|
bool
|
If |
True
|
use_binned_residuals
|
bool
|
If |
True
|
random_state
|
int
|
Seed for the random number generator to ensure reproducibility. |
123
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Distribution parameters estimated for each step. |
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 | |
predict_interval(steps, last_window=None, exog=None, method='bootstrapping', interval=[5, 95], n_boot=250, use_in_sample_residuals=True, use_binned_residuals=True, random_state=123)
Predict n steps ahead and estimate prediction intervals using either bootstrapping or conformal prediction methods. Refer to the References section for additional details on these methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int | str | Timestamp
|
Number of steps to predict. - If steps is int, number of steps to predict. - If str or pandas Datetime, the prediction will be up to that date. |
required |
last_window
|
Series | DataFrame | None
|
Series values used to create the predictors (lags) needed in the
first iteration of the prediction (t + 1).
If |
None
|
exog
|
Series | DataFrame | None
|
Exogenous variable/s included as predictor/s. Defaults to None. |
None
|
method
|
str
|
Technique used to estimate prediction intervals. Available options: - 'bootstrapping': Bootstrapping is used to generate prediction intervals [1]. - 'conformal': Employs the conformal prediction split method for interval estimation [2]. Defaults to 'bootstrapping'. |
'bootstrapping'
|
interval
|
float | list[float] | tuple[float]
|
Confidence level of the prediction interval. Interpretation depends
on the method used:
- If |
[5, 95]
|
n_boot
|
int
|
Number of bootstrapping iterations to perform when estimating prediction intervals. Defaults to 250. |
250
|
use_in_sample_residuals
|
bool
|
If |
True
|
use_binned_residuals
|
bool
|
If |
True
|
random_state
|
int
|
Seed for the random number generator to ensure reproducibility. Defaults to 123. |
123
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Pandas DataFrame with values predicted by the forecaster and their estimated interval. |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ValueError
|
If |
ValueError
|
If inputs ( |
Examples:
>>> import numpy as np
>>> import pandas as pd
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> rng = np.random.default_rng(123)
>>> y = pd.Series(rng.normal(size=100), name='y')
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> _ = forecaster.fit(y=y)
>>> # Bootstrapping method
>>> intervals_boot = forecaster.predict_interval(
... steps=3, method='bootstrapping', interval=[5, 95]
... )
>>> intervals_boot.columns.tolist()
['pred', 'lower_bound', 'upper_bound']
>>> # Conformal method
>>> intervals_conf = forecaster.predict_interval(
... steps=3, method='conformal', interval=0.95
... )
>>> intervals_conf.columns.tolist()
['pred', 'lower_bound', 'upper_bound']
References
.. [1] Forecasting: Principles and Practice (3rd ed) Rob J Hyndman and George Athanasopoulos. https://otexts.com/fpp3/prediction-intervals.html .. [2] MAPIE - Model Agnostic Prediction Interval Estimator. https://mapie.readthedocs.io/en/stable/theoretical_description_regression.html#the-split-method
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 | |
predict_quantiles(steps, last_window=None, exog=None, quantiles=[0.05, 0.5, 0.95], n_boot=250, use_in_sample_residuals=True, use_binned_residuals=True, random_state=123)
Calculate the specified quantiles for each step. After generating multiple forecasting predictions through a bootstrapping process, each quantile is calculated for each step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
int | str | Timestamp
|
Number of steps to predict. - If steps is int, number of steps to predict. - If str or pandas Datetime, the prediction will be up to that date. |
required |
last_window
|
Series | DataFrame | None
|
Series values used to create the predictors (lags) needed in the
first iteration of the prediction (t + 1).
If |
None
|
exog
|
Series | DataFrame | None
|
Exogenous variable/s included as predictor/s. |
None
|
quantiles
|
list[float] | tuple[float]
|
Sequence of quantiles to compute, which must be between 0 and 1
inclusive. For example, quantiles of 0.05, 0.5 and 0.95 should be as
|
[0.05, 0.5, 0.95]
|
n_boot
|
int
|
Number of bootstrapping iterations to perform when estimating quantiles. |
250
|
use_in_sample_residuals
|
bool
|
If |
True
|
use_binned_residuals
|
bool
|
If |
True
|
random_state
|
int
|
Seed for the random number generator to ensure reproducibility. |
123
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Quantiles predicted by the forecaster. |
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
set_fit_kwargs(fit_kwargs)
Set new values for the additional keyword arguments passed to the fit
method of the estimator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fit_kwargs
|
dict[str, object]
|
Dict of the form {"argument": new_value}. |
required |
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
set_in_sample_residuals(y, exog=None, random_state=123)
Set in-sample residuals in case they were not calculated during the training process.
In-sample residuals are calculated as the difference between the true values and the predictions made by the forecaster using the training data. The following internal attributes are updated:
in_sample_residuals_: residuals stored in a numpy ndarray.binner_intervals_: intervals used to bin the residuals are calculated using the quantiles of the predicted values.in_sample_residuals_by_bin_: residuals are binned according to the predicted value they are associated with and stored in a dictionary, where the keys are the intervals of the predicted values and the values are the residuals associated with that range.
A total of 10_000 residuals are stored in the attribute in_sample_residuals_.
If the number of residuals is greater than 10_000, a random sample of
10_000 residuals is stored. The number of residuals stored per bin is
limited to 10_000 // self.binner.n_bins_.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Series
|
Target time series. |
required |
exog: Exogenous variables.
random_state: Random state for reproducibility.
Returns:
| Type | Description |
|---|---|
None
|
None |
Raises:
| Type | Description |
|---|---|
NotFittedError
|
If the forecaster is not fitted. |
IndexError
|
If the index range of |
ValueError
|
If the features generated from the provided data do not match those used during the training process. |
Examples:
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> forecaster.fit(y=pd.Series(np.arange(20)), store_in_sample_residuals=False)
>>> forecaster.set_in_sample_residuals(y=pd.Series(np.arange(20)))
>>> forecaster.in_sample_residuals_
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 | |
set_lags(lags=None)
Set new value to the attribute lags. Attributes lags_names,
max_lag and window_size are also updated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lags
|
Union[int, List[int], ndarray, range, None]
|
Lags used as predictors. Index starts at 1, so lag 1 is equal to t-1.
- |
None
|
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
set_out_sample_residuals(y_true, y_pred, append=False, random_state=123)
Set new values to the attribute out_sample_residuals_.
Out of sample residuals are meant to be calculated using observations that
did not participate in the training process. y_true and y_pred are
expected to be in the original scale of the time series. Residuals are
calculated as y_true - y_pred, after applying the necessary
transformations and differentiations if the forecaster includes them
(self.transformer_y and self.differentiation). Two internal attributes
are updated:
out_sample_residuals_: residuals stored in a numpy ndarray.out_sample_residuals_by_bin_: residuals are binned according to the predicted value they are associated with and stored in a dictionary, where the keys are the intervals of the predicted values and the values are the residuals associated with that range. If a bin is empty, it is filled with a random sample of residuals from other bins. This is done to ensure that all bins have at least one residual and can be used in the prediction process.
A total of 10_000 residuals are stored in the attribute out_sample_residuals_.
If the number of residuals is greater than 10_000, a random sample of
10_000 residuals is stored. The number of residuals stored per bin is
limited to 10_000 // self.binner.n_bins_.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
ndarray | Series
|
True values of the time series in the original scale. |
required |
y_pred
|
ndarray | Series
|
Predicted values of the time series in the original scale. |
required |
append
|
bool
|
If |
False
|
random_state
|
int
|
Random state for reproducibility. |
123
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Raises:
| Type | Description |
|---|---|
NotFittedError
|
If the forecaster is not fitted. |
TypeError
|
If |
ValueError
|
If |
Examples:
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> import pandas as pd
>>> import numpy as np
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> forecaster.fit(y=pd.Series(np.arange(20)), store_in_sample_residuals=False)
>>> y_true = np.array([20, 21, 22, 23, 24])
>>> y_pred = np.array([20.1, 20.9, 22.2, 22.8, 24.0])
>>> forecaster.set_out_sample_residuals(y_true=y_true, y_pred=y_pred)
>>> forecaster.out_sample_residuals_
array([-0.1, 0.1, -0.2, 0.2, 0. ])
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 | |
set_params(params=None, **kwargs)
Set the parameters of this forecaster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
Dict[str, object]
|
Optional dictionary of parameter names mapped to their new values. If provided, these parameters are set first. |
None
|
**kwargs
|
object
|
Dictionary of parameter names mapped to their new values.
Parameters can be for the forecaster itself or for the contained estimator (using the |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
'ForecasterRecursive'
|
The forecaster instance with updated parameters. |
Examples:
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> forecaster = ForecasterRecursive(estimator=LinearRegression(), lags=3)
>>> forecaster.set_params(estimator__fit_intercept=False)
>>> forecaster.estimator.get_params()["fit_intercept"]
False
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
set_window_features(window_features=None)
Set new value to the attribute window_features. Attributes
max_size_window_features, window_features_names,
window_features_class_names and window_size are also updated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_features
|
object | list[object] | None
|
Instance or list of instances used to create window features. Window features are created from the original time series and are included as predictors. |
None
|
Source code in src/spotforecast2_safe/forecaster/recursive/_forecaster_recursive.py
Forecasting Utilities
utils
spotforecast2_safe.forecaster.utils
check_exog(exog, allow_nan=True, series_id='`exog`')
Validate that exog is a pandas Series or DataFrame.
This function ensures that exogenous variables meet basic requirements: - Must be a pandas Series or DataFrame - If Series, must have a name - Optionally warns if NaN values are present
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exog
|
Union[Series, DataFrame]
|
Exogenous variable/s included as predictor/s. |
required |
allow_nan
|
bool
|
If True, allows NaN values but issues a warning. If False, raises no warning about NaN values. Defaults to True. |
True
|
series_id
|
str
|
Identifier of the series used in error messages. Defaults to " |
'`exog`'
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If exog is not a pandas Series or DataFrame. |
ValueError
|
If exog is a Series without a name. |
Warns:
| Type | Description |
|---|---|
MissingValuesWarning
|
If allow_nan=True and exog contains NaN values. |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from spotforecast2_safe.utils.validation import check_exog
>>>
>>> # Valid DataFrame
>>> exog_df = pd.DataFrame({"temp": [20, 21, 22], "humidity": [50, 55, 60]})
>>> check_exog(exog_df) # No error
>>>
>>> # Valid Series with name
>>> exog_series = pd.Series([1, 2, 3], name="temperature")
>>> check_exog(exog_series) # No error
>>>
>>> # Invalid: Series without name
>>> exog_no_name = pd.Series([1, 2, 3])
>>> try:
... check_exog(exog_no_name)
... except ValueError as e:
... print(f"Error: {e}")
Error: When `exog` is a pandas Series, it must have a name.
>>>
>>> # Invalid: not a Series/DataFrame
>>> try:
... check_exog([1, 2, 3])
... except TypeError as e:
... print(f"Error: {e}")
Error: `exog` must be a pandas Series or DataFrame. Got <class 'list'>.
Source code in src/spotforecast2_safe/utils/validation.py
check_exog_dtypes(exog, call_check_exog=True, series_id='`exog`')
Check that exogenous variables have valid data types (int, float, category).
This function validates that the exogenous variables (Series or DataFrame) contain only supported data types: integer, float, or category. It issues a warning if other types (like object/string) are found, as these may cause issues with some machine learning estimators.
It also strictly enforces that categorical columns must have integer categories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exog
|
Union[Series, DataFrame]
|
Exogenous variables to check. |
required |
call_check_exog
|
bool
|
If True, calls check_exog() first to ensure basic validity. Defaults to True. |
True
|
series_id
|
str
|
Identifier used in warning/error messages. Defaults to " |
'`exog`'
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If categorical columns contain non-integer categories. |
Warns:
| Type | Description |
|---|---|
DataTypeWarning
|
If columns with unsupported data types (not int, float, category) are found. |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from spotforecast2_safe.utils.validation import check_exog_dtypes
>>>
>>> # Valid types (float, int)
>>> df_valid = pd.DataFrame({
... "a": [1.0, 2.0, 3.0],
... "b": [1, 2, 3]
... })
>>> check_exog_dtypes(df_valid) # No warning
>>>
>>> # Invalid type (object/string)
>>> df_invalid = pd.DataFrame({
... "a": [1, 2, 3],
... "b": ["x", "y", "z"]
... })
>>> check_exog_dtypes(df_invalid)
... # Issues DataTypeWarning about column 'b'
>>>
>>> # Valid categorical (with integer categories)
>>> df_cat = pd.DataFrame({"a": [1, 2, 1]})
>>> df_cat["a"] = df_cat["a"].astype("category")
>>> check_exog_dtypes(df_cat) # No warning
Source code in src/spotforecast2_safe/utils/validation.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | |
check_extract_values_and_index(data, data_label='`y`', ignore_freq=False, return_values=True)
Extract values and index from a pandas Series or DataFrame, ensuring they are valid.
Validates that the input data has a proper DatetimeIndex or RangeIndex and extracts its values and index for use in forecasting operations. Optionally checks for index frequency consistency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[Series, DataFrame]
|
Input data (pandas Series or DataFrame) to extract values and index from. |
required |
data_label
|
str
|
Label used in exception messages for better error reporting.
Defaults to " |
'`y`'
|
ignore_freq
|
bool
|
If True, the frequency of the index is not checked. Defaults to False. |
False
|
return_values
|
bool
|
If True, the values of the data are returned. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
Tuple[Optional[ndarray], Index]
|
A tuple containing: - values (numpy.ndarray or None): Values of the data as numpy array, or None if return_values is False. - index (pandas.Index): Index of the data. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If data is not a pandas Series or DataFrame. |
TypeError
|
If data index is not a DatetimeIndex or RangeIndex. |
Warns:
| Type | Description |
|---|---|
UserWarning
|
If DatetimeIndex has no frequency (inferred automatically). |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> dates = pd.date_range('2020-01-01', periods=10, freq='D')
>>> series = pd.Series(np.arange(10), index=dates)
>>> values, index = check_extract_values_and_index(series)
>>> print(values.shape)
(10,)
>>> print(type(index))
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>
Extract index only:
>>> _, index = check_extract_values_and_index(series, return_values=False)
>>> print(index[0])
2020-01-01 00:00:00
Source code in src/spotforecast2_safe/forecaster/utils.py
check_interval(interval=None, ensure_symmetric_intervals=False, quantiles=None, alpha=None, alpha_literal='alpha')
Validate that a confidence interval specification is valid.
This function checks that interval values are properly formatted and within valid ranges for confidence interval prediction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
Union[List[float], Tuple[float], None]
|
Confidence interval percentiles (0-100 inclusive). Should be [lower_bound, upper_bound]. Example: [2.5, 97.5] for 95% interval. |
None
|
ensure_symmetric_intervals
|
bool
|
If True, ensure intervals are symmetric (lower + upper = 100). |
False
|
quantiles
|
Union[List[float], Tuple[float], None]
|
Sequence of quantiles (0-1 inclusive). Currently not validated, reserved for future use. |
None
|
alpha
|
Optional[float]
|
Confidence level (1-alpha). Currently not validated, reserved for future use. |
None
|
alpha_literal
|
Optional[str]
|
Name used in error messages for alpha parameter. |
'alpha'
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If interval is not a list or tuple. |
ValueError
|
If interval doesn't have exactly 2 values, values out of range (0-100), lower >= upper, or intervals not symmetric when required. |
Examples:
>>> from spotforecast2_safe.utils.validation import check_interval
>>>
>>> # Valid 95% confidence interval
>>> check_interval(interval=[2.5, 97.5]) # No error
>>>
>>> # Valid symmetric interval
>>> check_interval(interval=[2.5, 97.5], ensure_symmetric_intervals=True) # No error
>>>
>>> # Invalid: not symmetric
>>> try:
... check_interval(interval=[5, 90], ensure_symmetric_intervals=True)
... except ValueError as e:
... print("Error: Interval not symmetric")
Error: Interval not symmetric
>>>
>>> # Invalid: wrong number of values
>>> try:
... check_interval(interval=[2.5, 50, 97.5])
... except ValueError as e:
... print("Error: Must have exactly 2 values")
Error: Must have exactly 2 values
>>>
>>> # Invalid: out of range
>>> try:
... check_interval(interval=[-5, 105])
... except ValueError as e:
... print("Error: Values out of range")
Error: Values out of range
Source code in src/spotforecast2_safe/utils/validation.py
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | |
check_predict_input(forecaster_name, steps, is_fitted, exog_in_, index_type_, index_freq_, window_size, last_window, last_window_exog=None, exog=None, exog_names_in_=None, interval=None, alpha=None, max_step=None, levels=None, levels_forecaster=None, series_names_in_=None, encoding=None)
Check all inputs of predict method. This is a helper function to validate that inputs used in predict method match attributes of a forecaster already trained.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forecaster_name
|
str
|
str Forecaster name. |
required |
steps
|
Union[int, List[int]]
|
int, list Number of future steps predicted. |
required |
is_fitted
|
bool
|
bool Tag to identify if the estimator has been fitted (trained). |
required |
exog_in_
|
bool
|
bool If the forecaster has been trained using exogenous variable/s. |
required |
index_type_
|
type
|
type Type of index of the input used in training. |
required |
index_freq_
|
str
|
str Frequency of Index of the input used in training. |
required |
window_size
|
int
|
int
Size of the window needed to create the predictors. It is equal to
|
required |
last_window
|
Optional[Union[Series, DataFrame]]
|
pandas Series, pandas DataFrame, None Values of the series used to create the predictors (lags) need in the first iteration of prediction (t + 1). |
required |
last_window_exog
|
Optional[Union[Series, DataFrame]]
|
pandas Series, pandas DataFrame, default None
Values of the exogenous variables aligned with |
None
|
exog
|
Optional[Union[Series, DataFrame, Dict[str, Union[Series, DataFrame]]]]
|
pandas Series, pandas DataFrame, dict, default None Exogenous variable/s included as predictor/s. |
None
|
exog_names_in_
|
Optional[List[str]]
|
list, default None Names of the exogenous variables used during training. |
None
|
interval
|
Optional[List[float]]
|
list, tuple, default None
Confidence of the prediction interval estimated. Sequence of percentiles
to compute, which must be between 0 and 100 inclusive. For example,
interval of 95% should be as |
None
|
alpha
|
Optional[float]
|
float, default None The confidence intervals used in ForecasterStats are (1 - alpha) %. |
None
|
max_step
|
Optional[int]
|
int, default None
Maximum number of steps allowed ( |
None
|
levels
|
Optional[Union[str, List[str]]]
|
str, list, default None
Time series to be predicted ( |
None
|
levels_forecaster
|
Optional[Union[str, List[str]]]
|
str, list, default None
Time series used as output data of a multiseries problem in a RNN problem
( |
None
|
series_names_in_
|
Optional[List[str]]
|
list, default None
Names of the columns used during fit ( |
None
|
encoding
|
Optional[str]
|
str, default None
Encoding used to identify the different series ( |
None
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Source code in src/spotforecast2_safe/utils/validation.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 | |
check_preprocess_series(series)
Check and preprocess series argument in ForecasterRecursiveMultiSeries class.
- If `series` is a wide-format pandas DataFrame, each column represents a
different time series, and the index must be either a `DatetimeIndex` or
a `RangeIndex` with frequency or step size, as appropriate
- If `series` is a long-format pandas DataFrame with a MultiIndex, the
first level of the index must contain the series IDs, and the second
level must be a `DatetimeIndex` with the same frequency across all series.
- If series is a dictionary, each key must be a series ID, and each value
must be a named pandas Series. All series must have the same index, which
must be either a `DatetimeIndex` or a `RangeIndex`, and they must share the
same frequency or step size, as appropriate.
When series is a pandas DataFrame, it is converted to a dictionary of pandas
Series, where the keys are the series IDs and the values are the Series with
the same index as the original DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
series
|
DataFrame | dict[str, Series | DataFrame]
|
pandas DataFrame or dictionary of pandas Series/DataFrames |
required |
Returns:
| Type | Description |
|---|---|
tuple[dict[str, Series], dict[str, Index]]
|
tuple[dict[str, pd.Series], dict[str, pd.Index]]: - series_dict: Dictionary where keys are series IDs and values are pandas Series. - series_indexes: Dictionary where keys are series IDs and values are the index of each series. |
Raises:
TypeError:
If series is not a pandas DataFrame or a dictionary of pandas Series/DataFrames.
TypeError:
If the index of series is not a DatetimeIndex or RangeIndex with frequency/step size.
ValueError:
If the series in series have different frequencies or step sizes.
ValueError:
If all values of any series are NaN.
UserWarning:
If series is a wide-format DataFrame, only the first column will be used as series values.
UserWarning:
If series is a DataFrame (either wide or long format), additional internal transformations are required, which can increase computational time.
It is recommended to use a dictionary of pandas Series instead.
Examples:
>>> import pandas as pd
>>> from spotforecast2_safe.forecaster.utils import check_preprocess_series
>>> # Example with wide-format DataFrame
>>> dates = pd.date_range('2020-01-01', periods=5, freq='D')
>>> df_wide = pd.DataFrame({
... 'series_1': [1, 2, 3, 4, 5],
... 'series_2': [5, 4, 3, 2, 1],
... }, index=dates)
>>> series_dict, series_indexes = check_preprocess_series(df_wide)
UserWarning: `series` DataFrame has multiple columns. Only the values of first column, 'series_1', will be used as series values. All other columns will be ignored.
UserWarning: Passing a DataFrame (either wide or long format) as `series` requires additional internal transformations, which can increase computational time.
It is recommended to use a dictionary of pandas Series instead.
>>> print(series_dict['series_1'])
2020-01-01 1
2020-01-02 2
2020-01-03 3
2020-01-04 4
2020-01-05 5
Name: series_1, dtype: int64
>>> print(series_indexes['series_1'])
DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04',
'2020-01-05'],
dtype='datetime64[ns]', freq='D')
>>> # Example with long-format DataFrame
>>> df_long = pd.DataFrame({
... 'series_id': ['series_1'] * 5 + ['series_2'] * 5,
... 'value': [1, 2, 3, 4, 5, 5, 4, 3, 2, 1],
... }, index=pd.MultiIndex.from_product([['series_1', 'series_2'], dates], names=['series_id', 'date']))
>>> series_dict, series_indexes = check_preprocess_series(df_long)
UserWarning: `series` DataFrame has multiple columns. Only the values of first column, 'value', will be used as series values. All other columns will be ignored.
UserWarning: Passing a DataFrame (either wide or long format) as `series` requires additional internal transformations, which can increase computational time.
It is recommended to use a dictionary of pandas Series instead.
>>> print(series_dict['series_1'])
2020-01-01 1
2020-01-02 2
2020-01-03 3
2020-01-04 4
2020-01-05 5
Name: series_1, dtype: int64
>>> print(series_indexes['series_1'])
DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04',
'2020-01-05'],
dtype='datetime64[ns]', freq='D')
>>> # Example with dictionary of Series
>>> series_dict_input = {
... 'series_1': pd.Series([1, 2, 3, 4, 5], index=dates),
... 'series_2': pd.Series([5, 4, 3, 2, 1], index=dates),
... }
>>> series_dict, series_indexes = check_preprocess_series(series_dict_input)
>>> print(series_dict['series_1'])
2020-01-01 1
2020-01-02 2
2020-01-03 3
2020-01-04 4
2020-01-05 5
Name: series_1, dtype: int64
>>> print(series_indexes['series_1'])
DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04',
'2020-01-05'],
dtype='datetime64[ns]', freq='D')
>>> # Example with dictionary of DataFrames
>>> df_series_1 = pd.DataFrame({'value': [1, 2, 3, 4, 5]}, index=dates)
>>> df_series_2 = pd.DataFrame({'value': [5, 4, 3, 2, 1]}, index=dates)
>>> series_dict_input = {
... 'series_1': df_series_1,
... 'series_2': df_series_2,
... }
>>> series_dict, series_indexes = check_preprocess_series(series_dict_input)
>>> print(series_dict['series_1'])
2020-01-01 1
2020-01-02 2
2020-01-03 3
2020-01-04 4
2020-01-05 5
Name: series_1, dtype: int64
>>> print(series_indexes['series_1'])
DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04',
'2020-01-05'],
dtype='datetime64[ns]', freq='D')
Source code in src/spotforecast2_safe/forecaster/utils.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | |
check_residuals_input(forecaster_name, use_in_sample_residuals, in_sample_residuals_, out_sample_residuals_, use_binned_residuals, in_sample_residuals_by_bin_, out_sample_residuals_by_bin_, levels=None, encoding=None)
Check residuals input arguments in Forecasters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forecaster_name
|
str
|
str Forecaster name. |
required |
use_in_sample_residuals
|
bool
|
bool Indicates if in sample or out sample residuals are used. |
required |
in_sample_residuals_
|
ndarray | dict[str, ndarray] | None
|
numpy ndarray, dict Residuals of the model when predicting training data. |
required |
out_sample_residuals_
|
ndarray | dict[str, ndarray] | None
|
numpy ndarray, dict Residuals of the model when predicting non training data. |
required |
use_binned_residuals
|
bool
|
bool Indicates if residuals are binned. |
required |
in_sample_residuals_by_bin_
|
dict[str | int, ndarray | dict[int, ndarray]] | None
|
dict In sample residuals binned according to the predicted value each residual is associated with. |
required |
out_sample_residuals_by_bin_
|
dict[str | int, ndarray | dict[int, ndarray]] | None
|
dict Out of sample residuals binned according to the predicted value each residual is associated with. |
required |
levels
|
list[str] | None
|
list, default None Names of the series (levels) to be predicted (Forecasters multiseries). |
None
|
encoding
|
str | None
|
str, default None Encoding used to identify the different series (ForecasterRecursiveMultiSeries). |
None
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
from spotforecast2_safe.forecaster.utils import check_residuals_input import numpy as np forecaster_name = "ForecasterRecursiveMultiSeries" use_in_sample_residuals = True in_sample_residuals_ = np.array([0.1, -0.2 out_sample_residuals_ = np.array([0.3, -0.1]) use_binned_residuals = False check_residuals_input( forecaster_name, use_in_sample_residuals, in_sample_residuals_, out_sample_residuals_, use_binned_residuals, in_sample_residuals_by_bin_=None, out_sample_residuals_by_bin_=None, levels=['series_1', 'series_2'], encoding='onehot' )
Source code in src/spotforecast2_safe/forecaster/utils.py
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 | |
check_select_fit_kwargs(estimator, fit_kwargs=None)
Check if fit_kwargs is a dict and select only keys used by estimator's fit.
This function validates that fit_kwargs is a dictionary, warns about unused arguments, removes 'sample_weight' (which should be handled via weight_func), and returns a dictionary containing only the arguments accepted by the estimator's fit method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
Any
|
Scikit-learn compatible estimator. |
required |
fit_kwargs
|
Optional[dict]
|
Dictionary of arguments to pass to the estimator's fit method. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with only the arguments accepted by the estimator's fit method. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If fit_kwargs is not a dict. |
Warns:
| Type | Description |
|---|---|
IgnoredArgumentWarning
|
If fit_kwargs contains keys not used by fit method, or if 'sample_weight' is present (it gets removed). |
Examples:
>>> from sklearn.linear_model import Ridge
>>> from spotforecast2_safe.utils.forecaster_config import check_select_fit_kwargs
>>>
>>> estimator = Ridge()
>>> # Valid argument for Ridge.fit
>>> kwargs = {"sample_weight": [1, 1], "invalid_arg": 10}
>>> # sample_weight is removed (should be passed via weight_func in forecaster)
>>> # invalid_arg is ignored
>>> filtered = check_select_fit_kwargs(estimator, kwargs)
>>> filtered
{}
Source code in src/spotforecast2_safe/utils/forecaster_config.py
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 | |
check_y(y, series_id='`y`')
Validate that y is a pandas Series without missing values.
This function ensures that the input time series meets the basic requirements for forecasting: it must be a pandas Series and must not contain any NaN values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Any
|
Time series values to validate. |
required |
series_id
|
str
|
Identifier of the series used in error messages. Defaults to " |
'`y`'
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If y is not a pandas Series. |
ValueError
|
If y contains missing (NaN) values. |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from spotforecast2_safe.utils.validation import check_y
>>>
>>> # Valid series
>>> y = pd.Series([1, 2, 3, 4, 5])
>>> check_y(y) # No error
>>>
>>> # Invalid: not a Series
>>> try:
... check_y([1, 2, 3])
... except TypeError as e:
... print(f"Error: {e}")
Error: `y` must be a pandas Series with a DatetimeIndex or a RangeIndex. Found <class 'list'>.
>>>
>>> # Invalid: contains NaN
>>> y_with_nan = pd.Series([1, 2, np.nan, 4])
>>> try:
... check_y(y_with_nan)
... except ValueError as e:
... print(f"Error: {e}")
Error: `y` has missing values.
Source code in src/spotforecast2_safe/utils/validation.py
date_to_index_position(index, date_input, method='prediction', date_literal='steps', kwargs_pd_to_datetime={})
Transform a datetime string or pandas Timestamp to an integer. The integer represents the position of the datetime in the index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
Index
|
pandas Index
Original datetime index (must be a pandas DatetimeIndex if |
required |
date_input
|
int | str | Timestamp
|
int, str, pandas Timestamp Datetime to transform to integer.
|
required |
method
|
str
|
str, default 'prediction' Can be 'prediction' or 'validation'.
|
'prediction'
|
date_literal
|
str
|
str, default 'steps' Variable name used in error messages. |
'steps'
|
kwargs_pd_to_datetime
|
dict
|
dict, default {}
Additional keyword arguments to pass to |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
|
int
|
|
|
int
|
|
|
int
|
date in the index. |
|
int
|
|
|
int
|
this is done to include the target date in the training set when using |
|
int
|
pandas iloc with slices. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
TypeError
|
If |
ValueError
|
If |
Examples:
from spotforecast2_safe.forecaster.utils import date_to_index_position import pandas as pd index = pd.date_range(start='2020-01-01', periods=10, freq='D')
Using an integer input
position = date_to_index_position(index, 5) print(position)
Output: 5
Using a date input for prediction
position = date_to_index_position(index, '2020-01-15', method='prediction') print(position)
Output: 5 (number of steps from the last date in the index to the target date)
Using a date input for validation
position = date_to_index_position(index, '2020-01-05', method='validation') print(position)
Output: 5 (position plus one of the target date in the index)
Source code in src/spotforecast2_safe/forecaster/utils.py
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 | |
exog_to_direct(exog, steps)
Transforms exog to a pandas DataFrame with the shape needed for Direct
forecasting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exog
|
Series | DataFrame
|
pandas Series, pandas DataFrame Exogenous variables. |
required |
steps
|
int
|
int Number of steps that will be predicted using exog. |
required |
Returns:
| Type | Description |
|---|---|
tuple[DataFrame, list[str]]
|
tuple[pd.DataFrame, list[str]]:
exog_direct: pandas DataFrame
Exogenous variables transformed.
exog_direct_names: list
Names of the columns of the exogenous variables transformed. Only
created if |
Source code in src/spotforecast2_safe/forecaster/utils.py
exog_to_direct_numpy(exog, steps)
Transforms exog to numpy ndarray with the shape needed for Direct
forecasting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exog
|
ndarray | Series | DataFrame
|
numpy ndarray, pandas Series, pandas DataFrame Exogenous variables, shape(samples,). If exog is a pandas format, the direct exog names are created. |
required |
steps
|
int
|
int Number of steps that will be predicted using exog. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, list[str] | None]
|
tuple[np.ndarray, list[str] | None]:
exog_direct: numpy ndarray
Exogenous variables transformed.
exog_direct_names: list, None
Names of the columns of the exogenous variables transformed. Only
created if |
Examples:
from spotforecast2_safe.forecaster.utils import exog_to_direct_numpy import numpy as np exog = np.array([10, 20, 30, 40, 50]) steps = 3 exog_direct, exog_direct_names = exog_to_direct_numpy(exog, steps) print(exog_direct) [[10 20 30] [20 30 40] [30 40 50]] print(exog_direct_names) None
Source code in src/spotforecast2_safe/forecaster/utils.py
expand_index(index, steps)
Create a new index extending from the end of the original index.
This function generates future indices for forecasting by extending the time series index by a specified number of steps. Handles both DatetimeIndex and RangeIndex appropriately.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
Union[Index, None]
|
Original pandas Index (DatetimeIndex or RangeIndex). If None, creates a RangeIndex starting from 0. |
required |
steps
|
int
|
Number of future steps to generate. |
required |
Returns:
| Type | Description |
|---|---|
Index
|
New pandas Index with |
Raises:
| Type | Description |
|---|---|
TypeError
|
If steps is not an integer, or if index is neither DatetimeIndex nor RangeIndex. |
Examples:
>>> import pandas as pd
>>> from spotforecast2_safe.utils.data_transform import expand_index
>>>
>>> # DatetimeIndex
>>> dates = pd.date_range("2023-01-01", periods=5, freq="D")
>>> new_index = expand_index(dates, 3)
>>> new_index
DatetimeIndex(['2023-01-06', '2023-01-07', '2023-01-08'], dtype='datetime64[ns]', freq='D')
>>>
>>> # RangeIndex
>>> range_idx = pd.RangeIndex(start=0, stop=10)
>>> new_index = expand_index(range_idx, 5)
>>> new_index
RangeIndex(start=10, stop=15, step=1)
>>>
>>> # None index (creates new RangeIndex)
>>> new_index = expand_index(None, 3)
>>> new_index
RangeIndex(start=0, stop=3, step=1)
>>>
>>> # Invalid: steps not an integer
>>> try:
... expand_index(dates, 3.5)
... except TypeError as e:
... print("Error: steps must be an integer")
Error: steps must be an integer
Source code in src/spotforecast2_safe/utils/data_transform.py
get_exog_dtypes(exog)
Extract and store the data types of exogenous variables.
This function returns a dictionary mapping column names to their data types. For Series, uses the series name as the key. For DataFrames, uses all column names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exog
|
Union[Series, DataFrame]
|
Exogenous variable/s (Series or DataFrame). |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, type]
|
Dictionary mapping variable names to their pandas dtypes. |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from spotforecast2_safe.utils.validation import get_exog_dtypes
>>>
>>> # DataFrame with mixed types
>>> exog_df = pd.DataFrame({
... "temp": pd.Series([20.5, 21.3, 22.1], dtype='float64'),
... "day": pd.Series([1, 2, 3], dtype='int64'),
... "is_weekend": pd.Series([False, False, True], dtype='bool')
... })
>>> dtypes = get_exog_dtypes(exog_df)
>>> dtypes['temp']
dtype('float64')
>>> dtypes['day']
dtype('int64')
>>>
>>> # Series
>>> exog_series = pd.Series([1.0, 2.0, 3.0], name="temperature", dtype='float64')
>>> dtypes = get_exog_dtypes(exog_series)
>>> dtypes
{'temperature': dtype('float64')}
Source code in src/spotforecast2_safe/utils/validation.py
get_style_repr_html(is_fitted=False)
Generate CSS style for HTML representation of the Forecaster.
Creates a unique CSS style block with a container ID for rendering forecaster objects in Jupyter notebooks or HTML documents. The styling provides a clean, monospace display with a light gray background.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
is_fitted
|
bool
|
Parameter to indicate if the Forecaster has been fitted. Currently not used in styling but reserved for future extensions. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
Tuple[str, str]
|
A tuple containing: - style (str): CSS style block as a string with unique container class. - unique_id (str): Unique 8-character ID for the container element. |
Examples:
>>> style, uid = get_style_repr_html(is_fitted=True)
>>> print(f"Container ID: {uid}")
Container ID: a1b2c3d4
>>> print(f"Style contains CSS: {'container-' in style}")
Style contains CSS: True
Using in HTML rendering:
>>> style, uid = get_style_repr_html(is_fitted=False)
>>> html = f"{style}<div class='container-{uid}'>Forecaster Info</div>"
>>> print("background-color" in html)
True
Source code in src/spotforecast2_safe/forecaster/utils.py
initialize_estimator(estimator=None, regressor=None)
Helper to handle the deprecation of 'regressor' in favor of 'estimator'. Returns the valid estimator object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
object | None
|
estimator or pipeline compatible with the scikit-learn API, default None An instance of a estimator or pipeline compatible with the scikit-learn API. |
None
|
regressor
|
object | None
|
estimator or pipeline compatible with the scikit-learn API, default None Deprecated. An instance of a estimator or pipeline compatible with the scikit-learn API. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
estimator or pipeline compatible with the scikit-learn API The valid estimator object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If both |
Warning
|
If |
Examples:
from spotforecast2_safe.forecaster.utils import initialize_estimator from sklearn.linear_model import LinearRegression
Using the estimator argument
estimator = LinearRegression() result = initialize_estimator(estimator=estimator) print(result) LinearRegression()
Using the deprecated regressor argument
regressor = LinearRegression() result = initialize_estimator(regressor=regressor) print(result) LinearRegression()
Source code in src/spotforecast2_safe/forecaster/utils.py
initialize_lags(forecaster_name, lags)
Validate and normalize lag specification for forecasting.
This function converts various lag specifications (int, list, tuple, range, ndarray) into a standardized format: sorted numpy array, lag names, and maximum lag value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forecaster_name
|
str
|
Name of the forecaster class for error messages. |
required |
lags
|
Any
|
Lag specification in one of several formats: - int: Creates lags from 1 to lags (e.g., 5 → [1,2,3,4,5]) - list/tuple/range: Converted to numpy array - numpy.ndarray: Validated and used directly - None: Returns (None, None, None) |
required |
Returns:
| Type | Description |
|---|---|
Optional[ndarray]
|
Tuple containing: |
Optional[List[str]]
|
|
Optional[int]
|
|
Tuple[Optional[ndarray], Optional[List[str]], Optional[int]]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If lags < 1, empty array, or not 1-dimensional. |
TypeError
|
If lags is not an integer, not in the right format for the forecaster, or array contains non-integer values. |
Examples:
>>> import numpy as np
>>> from spotforecast2_safe.utils.forecaster_config import initialize_lags
>>>
>>> # Integer input
>>> lags, names, max_lag = initialize_lags("ForecasterRecursive", 3)
>>> lags
array([1, 2, 3])
>>> names
['lag_1', 'lag_2', 'lag_3']
>>> max_lag
3
>>>
>>> # List input
>>> lags, names, max_lag = initialize_lags("ForecasterRecursive", [1, 3, 5])
>>> lags
array([1, 3, 5])
>>> names
['lag_1', 'lag_3', 'lag_5']
>>>
>>> # Range input
>>> lags, names, max_lag = initialize_lags("ForecasterRecursive", range(1, 4))
>>> lags
array([1, 2, 3])
>>>
>>> # None input
>>> lags, names, max_lag = initialize_lags("ForecasterRecursive", None)
>>> lags is None
True
>>>
>>> # Invalid: lags < 1
>>> try:
... initialize_lags("ForecasterRecursive", 0)
... except ValueError as e:
... print("Error: Minimum value of lags allowed is 1")
Error: Minimum value of lags allowed is 1
>>>
>>> # Invalid: negative lags
>>> try:
... initialize_lags("ForecasterRecursive", [1, -2, 3])
... except ValueError as e:
... print("Error: Minimum value of lags allowed is 1")
Error: Minimum value of lags allowed is 1
Source code in src/spotforecast2_safe/utils/forecaster_config.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
initialize_transformer_series(forecaster_name, series_names_in_, encoding=None, transformer_series=None)
Initialize transformer_series_ attribute for multivariate/multiseries forecasters.
Creates a dictionary of transformers for each time series in multivariate or multiseries forecasting. Handles three cases: no transformation (None), same transformer for all series (single object), or different transformers per series (dictionary). Clones transformer objects to avoid overwriting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forecaster_name
|
str
|
Name of the forecaster using this function. Special handling is applied for 'ForecasterRecursiveMultiSeries'. |
required |
series_names_in_
|
list[str]
|
Names of the time series (levels) used during training. These will be the keys in the returned transformer dictionary. |
required |
encoding
|
str | None
|
Encoding used to identify different series. Only used for ForecasterRecursiveMultiSeries. If None, creates a single '_unknown_level' entry. Defaults to None. |
None
|
transformer_series
|
object | dict[str, object | None] | None
|
Transformer(s) to apply to series. Can be: - None: No transformation applied - Single transformer object: Same transformer cloned for all series - Dict mapping series names to transformers: Different transformer per series Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, object | None]
|
Dictionary with series names as keys and transformer objects (or None) as values. Transformers are cloned to prevent overwriting. |
Warns:
| Type | Description |
|---|---|
IgnoredArgumentWarning
|
If transformer_series is a dict and some series_names_in_ are not present in the dict keys (those series get no transformation). |
Examples:
No transformation:
>>> from spotforecast2_safe.forecaster.utils import initialize_transformer_series
>>> series = ['series1', 'series2', 'series3']
>>> result = initialize_transformer_series(
... forecaster_name='ForecasterDirectMultiVariate',
... series_names_in_=series,
... transformer_series=None
... )
>>> print(result)
{'series1': None, 'series2': None, 'series3': None}
Same transformer for all series:
>>> from sklearn.preprocessing import StandardScaler
>>> scaler = StandardScaler()
>>> result = initialize_transformer_series(
... forecaster_name='ForecasterDirectMultiVariate',
... series_names_in_=['series1', 'series2'],
... transformer_series=scaler
... )
>>> len(result)
2
>>> all(isinstance(v, StandardScaler) for v in result.values())
True
>>> result['series1'] is result['series2'] # Different clones
False
Different transformer per series:
>>> from sklearn.preprocessing import MinMaxScaler
>>> transformers = {
... 'series1': StandardScaler(),
... 'series2': MinMaxScaler()
... }
>>> result = initialize_transformer_series(
... forecaster_name='ForecasterDirectMultiVariate',
... series_names_in_=['series1', 'series2'],
... transformer_series=transformers
... )
>>> isinstance(result['series1'], StandardScaler)
True
>>> isinstance(result['series2'], MinMaxScaler)
True
Source code in src/spotforecast2_safe/forecaster/utils.py
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 | |
initialize_weights(forecaster_name, estimator, weight_func, series_weights)
Validate and initialize weight function configuration for forecasting.
This function validates weight_func and series_weights, extracts source code from weight functions for serialization, and checks if the estimator supports sample weights in its fit method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forecaster_name
|
str
|
Name of the forecaster class. |
required |
estimator
|
Any
|
Scikit-learn compatible estimator or pipeline. |
required |
weight_func
|
Any
|
Weight function specification: - Callable: Single weight function - dict: Dictionary of weight functions (for MultiSeries forecasters) - None: No weighting |
required |
series_weights
|
Any
|
Dictionary of series-level weights (for MultiSeries forecasters). - dict: Maps series names to weight values - None: No series weighting |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Tuple containing: |
Optional[Union[str, dict]]
|
|
Any
|
|
Tuple[Any, Optional[Union[str, dict]], Any]
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If weight_func is not Callable/dict (depending on forecaster type), or if series_weights is not a dict. |
Warns:
| Type | Description |
|---|---|
IgnoredArgumentWarning
|
If estimator doesn't support sample_weight. |
Examples:
>>> import numpy as np
>>> from sklearn.linear_model import Ridge
>>> from spotforecast2_safe.utils.forecaster_config import initialize_weights
>>>
>>> # Simple weight function
>>> def custom_weights(index):
... return np.ones(len(index))
>>>
>>> estimator = Ridge()
>>> wf, source, sw = initialize_weights(
... "ForecasterRecursive", estimator, custom_weights, None
... )
>>> wf is not None
True
>>> isinstance(source, str)
True
>>>
>>> # No weight function
>>> wf, source, sw = initialize_weights(
... "ForecasterRecursive", estimator, None, None
... )
>>> wf is None
True
>>> source is None
True
>>>
>>> # Invalid type for non-MultiSeries forecaster
>>> try:
... initialize_weights("ForecasterRecursive", estimator, "invalid", None)
... except TypeError as e:
... print("Error: weight_func must be Callable")
Error: weight_func must be Callable
Source code in src/spotforecast2_safe/utils/forecaster_config.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | |
initialize_window_features(window_features)
Check window_features argument input and generate the corresponding list.
This function validates window feature objects and extracts their metadata, ensuring they have the required attributes (window_sizes, features_names) and methods (transform_batch, transform) for proper forecasting operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_features
|
Any
|
Classes used to create window features. Can be a single
object or a list of objects. Each object must have |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
Tuple[Optional[List[object]], Optional[List[str]], Optional[int]]
|
A tuple containing:
- window_features (list or None): List of classes used to create window features.
- window_features_names (list or None): List with all the features names of the window features.
- max_size_window_features (int or None): Maximum value of the |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ValueError
|
If a window feature is missing required attributes or methods. |
TypeError
|
If |
Examples:
>>> from spotforecast2_safe.forecaster.preprocessing import RollingFeatures
>>> wf = RollingFeatures(stats=['mean', 'std'], window_sizes=[7, 14])
>>> wf_list, names, max_size = initialize_window_features(wf)
>>> print(f"Max window size: {max_size}")
Max window size: 14
>>> print(f"Number of features: {len(names)}")
Number of features: 4
Multiple window features:
>>> wf1 = RollingFeatures(stats=['mean'], window_sizes=7)
>>> wf2 = RollingFeatures(stats=['max', 'min'], window_sizes=3)
>>> wf_list, names, max_size = initialize_window_features([wf1, wf2])
>>> print(f"Max window size: {max_size}")
Max window size: 7
Source code in src/spotforecast2_safe/forecaster/utils.py
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 | |
input_to_frame(data, input_name)
Convert input data to a pandas DataFrame.
This function ensures consistent DataFrame format for internal processing. If data is already a DataFrame, it's returned as-is. If it's a Series, it's converted to a single-column DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[Series, DataFrame]
|
Input data as pandas Series or DataFrame. |
required |
input_name
|
str
|
Name of the input data type. Accepted values are: - 'y': Target time series - 'last_window': Last window for prediction - 'exog': Exogenous variables |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame version of the input data. For Series input, uses the series |
DataFrame
|
name if available, otherwise uses a default name based on input_name. |
Examples:
>>> import pandas as pd
>>> from spotforecast2_safe.utils.data_transform import input_to_frame
>>>
>>> # Series with name
>>> y = pd.Series([1, 2, 3], name="sales")
>>> df = input_to_frame(y, input_name="y")
>>> df.columns.tolist()
['sales']
>>>
>>> # Series without name (uses default)
>>> y_no_name = pd.Series([1, 2, 3])
>>> df = input_to_frame(y_no_name, input_name="y")
>>> df.columns.tolist()
['y']
>>>
>>> # DataFrame (returned as-is)
>>> df_input = pd.DataFrame({"temp": [20, 21], "humidity": [50, 55]})
>>> df_output = input_to_frame(df_input, input_name="exog")
>>> df_output.columns.tolist()
['temp', 'humidity']
>>>
>>> # Exog series without name
>>> exog = pd.Series([10, 20, 30])
>>> df_exog = input_to_frame(exog, input_name="exog")
>>> df_exog.columns.tolist()
['exog']
Source code in src/spotforecast2_safe/utils/data_transform.py
predict_multivariate(forecasters, steps_ahead, exog=None, show_progress=False)
Generate multi-output predictions using multiple baseline forecasters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forecasters
|
dict
|
Dictionary of fitted forecaster instances (one per target). Keys are target names, values are the fitted forecasters (e.g., ForecasterRecursive, ForecasterEquivalentDate). |
required |
steps_ahead
|
int
|
Number of steps to forecast. |
required |
exog
|
DataFrame
|
Exogenous variables for prediction. If provided, will be passed to each forecaster's predict method. |
None
|
show_progress
|
bool
|
Show progress bar while predicting per target forecaster. Default: False. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: DataFrame with predictions for all targets. |
Examples:
>>> import pandas as pd
>>> from sklearn.linear_model import LinearRegression
>>> from spotforecast2_safe.forecaster.recursive import ForecasterRecursive
>>> from spotforecast2_safe.forecaster.utils import predict_multivariate
>>> y1 = pd.Series([1, 2, 3, 4, 5])
>>> y2 = pd.Series([2, 4, 6, 8, 10])
>>> f1 = ForecasterRecursive(estimator=LinearRegression(), lags=2)
>>> f2 = ForecasterRecursive(estimator=LinearRegression(), lags=2)
>>> f1.fit(y=y1)
>>> f2.fit(y=y2)
>>> forecasters = {'target1': f1, 'target2': f2}
>>> predictions = predict_multivariate(forecasters, steps_ahead=2)
>>> predictions
target1 target2
5 6.0 12.0
6 7.0 14.0
Source code in src/spotforecast2_safe/forecaster/utils.py
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 | |
prepare_steps_direct(max_step, steps=None)
Prepare list of steps to be predicted in Direct Forecasters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_step
|
int | list[int] | ndarray
|
int, list, numpy ndarray Maximum number of future steps the forecaster will predict when using predict methods. |
required |
steps
|
int | list[int] | None
|
int, list, None, default None
Predict n steps. The value of
|
None
|
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: Steps to be predicted. |
Examples:
from spotforecast2_safe.forecaster.utils import prepare_steps_direct max_step = 5 steps = 3 steps_direct = prepare_steps_direct(max_step, steps) print(steps_direct) [1, 2, 3]
max_step = 5 steps = [1, 3, 5] steps_direct = prepare_steps_direct(max_step, steps) print(steps_direct) [1, 3, 5]
max_step = 5 steps = None steps_direct = prepare_steps_direct(max_step, steps) print(steps_direct) [1, 2, 3, 4, 5]
Source code in src/spotforecast2_safe/forecaster/utils.py
select_n_jobs_fit_forecaster(forecaster_name, estimator)
Select the number of jobs to run in parallel during the fit process.
This function determines the optimal number of parallel processes for fitting the forecaster based on the available system resources. In safety-critical environments, this helps manage computational load and ensures system predictability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forecaster_name
|
str
|
Name of the forecaster being fitted. Currently unused but reserved for granular resource allocation based on model complexity. |
required |
estimator
|
object
|
The estimator object being used by the forecaster. Currently unused but reserved for checking if the estimator itself supports internal parallelism. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The number of jobs (CPUs) to use for parallel processing. Defaults to |
int
|
the system CPU count, with a fallback to 1 if the count cannot be |
int
|
determined. |
Source code in src/spotforecast2_safe/forecaster/utils.py
set_skforecast_warnings(suppress_warnings, action='ignore')
Suppress spotforecast warnings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
suppress_warnings
|
bool
|
bool If True, spotforecast warnings will be suppressed. |
required |
action
|
str
|
str, default 'ignore' Action to take regarding the warnings. |
'ignore'
|
Source code in src/spotforecast2_safe/exceptions.py
transform_dataframe(df, transformer, fit=False, inverse_transform=False)
Transform raw values of pandas DataFrame with a scikit-learn alike transformer, preprocessor or ColumnTransformer.
The transformer used must have the following methods: fit, transform, fit_transform and inverse_transform. ColumnTransformers are not allowed since they do not have inverse_transform method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame to be transformed. |
required |
transformer
|
object
|
Scikit-learn alike transformer, preprocessor, or ColumnTransformer. Must implement fit, transform, fit_transform and inverse_transform. |
required |
fit
|
bool
|
Train the transformer before applying it. Defaults to False. |
False
|
inverse_transform
|
bool
|
Transform back the data to the original representation. This is not available when using transformers of class scikit-learn ColumnTransformers. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Transformed DataFrame. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If df is not a pandas DataFrame. |
ValueError
|
If inverse_transform is requested for ColumnTransformer. |
Source code in src/spotforecast2_safe/utils/data_transform.py
transform_numpy(array, transformer, fit=False, inverse_transform=False)
Transform raw values of a numpy ndarray with a scikit-learn alike transformer, preprocessor or ColumnTransformer. The transformer used must have the following methods: fit, transform, fit_transform and inverse_transform. ColumnTransformers are not allowed since they do not have inverse_transform method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
ndarray
|
numpy ndarray Array to be transformed. |
required |
transformer
|
object | None
|
scikit-learn alike transformer, preprocessor, or ColumnTransformer. Scikit-learn alike transformer (preprocessor) with methods: fit, transform, fit_transform and inverse_transform. |
required |
fit: bool, default False Train the transformer before applying it. inverse_transform: bool, default False Transform back the data to the original representation. This is not available when using transformers of class scikit-learn ColumnTransformers.
Returns:
| Type | Description |
|---|---|
ndarray
|
numpy ndarray: Transformed array. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
TypeError
|
If |
ValueError
|
If |
Examples:
ffrom spotforecast2_safe.forecaster.utils import transform_numpy from sklearn.preprocessing import StandardScaler import numpy as np array = np.array([[1, 2], [3, 4], [5, 6]]) transformer = StandardScaler() array_transformed = transform_numpy(array, transformer, fit=True) print(array_transformed) [[-1.22474487 -1.22474487] [ 0. 0. ] [ 1.22474487 1.22474487]] array_inversed = transform_numpy(array_transformed, transformer, inverse_transform=True) print(array_inversed) [[1. 2.] [3. 4.] [5. 6.]]
Source code in src/spotforecast2_safe/forecaster/utils.py
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 | |